I have a 2d array filled with global variables.
#define GRID_WIDTH 19
#define GRID_HEIGHT 10
char grid[GRID_WIDTH][GRID_HEIGHT];
Later in the code i use this 2d array
void Grid::ResetGrid()
{
// Empty the console screen
system("cls");
// Fills the grid with '#' walls
for (int i=0; i<GRID_WIDTH; i++)
{
for(int j = 0; j <GRID_HEIGHT; j++)
grid[i][j] = '#';
}
ir = 2;
}
While I'm running the program, i use watches and breakpoints. In the beginning the watch on grid said:
Name: grid
Value: [0] "###################"
[0] '#'
[1] '#'
[2] '#'
//and so on, i could expand it and look at every part of the array
type: char
but now it's broken and it only shows this:
Name: grid
Value: {...}
type: Grid
The strange thing is I didn't change the array code, only wrote code lines of compare to what's inside the array.
The code of printing it to the console:
void Grid::PrintGrid(int currentX, int currentY )
{
// Empty the console screen
system("cls");
// Displays the finished maze to the screen.
for (int y=0; y < GRID_HEIGHT; y++)
{
for (int x=0; x < GRID_WIDTH; x++)
{
cout << grid[x][y];
}
cout << endl;
}
// Just for testing, which direction and on what position the solver is
cout << ir << " " << currentX << "," << currentY;
}
The question is:
Why I can't see the information in the 2d array anymore in the watch or when I hoofer over?
I hope you can help me.
I don't think the problem happens to your codes posted out, because I just tested them in my visual stuido 2008, they runs well by your printGrid function, except varable ir I defined it gloably, and your printGrid function double defined x, and y, you defined it in function head, but in the loop, using for (int x...), which means no sense..
the result just come from the printGird is like this:
###################
###################
###################
###################
###################
###################
###################
###################
###################
###################
2 3,4请按任意键继续. . .
3, 4 is the value of x, y which passed in printGrid when using it.
It looks like your print code is going out of the bounds of the array. Much like when you're filling the array, you should use
for (int y=0; y < GRID_HEIGHT; ++y)
{
for (int x=0; x < GRID_WIDTH; ++x)
{
That may be the cause of your faulty print.
The question was why I couldn't see my 2d array anymore in the watch.
It's working again. Don't know what was wrong. But the image below shows the correct use of the watch. I use this to check the information inside the 2d array. But it didn't show information for a while just grid {...} instead of grid 0x00 char (* grid)[25] and then the information about the rows and columns.
Related
I have been trying to make asteroids in the console, I know that the console isn't an ideal way to do this, but I wanted to challenge myself.
The problem I am having is with printing to the screen. At first, my screen was flickering because I wasn't updating certain screen parts and instead redrawing every frame by appending the whole array to a string and outputting that string.
So I changed my code to do that, but my current problem now is that the fps of my game is really low because I can't batch call it to one cout function.
To print my code to the screen I have a 2d array of characters with width and height as its size. Then I copy the array, change the output, and compare it to the previous output to see if the pixel needs to be changed, then change it.
Here is my draw function
void draw() {
char prevOutput[ArrayBorder][ArrayBorder];
copyOutput(outputBuffer, prevOutput);
innitOutput();
plotPolygons();
for (int y = 0; y < GameBorder; y++) {
for (int x = 0; x < GameBorder; x++) {
if (outputBuffer[x][y] == prevOutput[x][y]) {continue;}
setCursorPosition(x, y);
cout << outputBuffer[x][y];
}
}
cout.flush();
}
Here is my previous draw function
void draw() {
innitOutput();
plotPolygons();
system("CLS");
string output = "";
for (int y = 0; y < GameBorder; y++) {
for (int x = 0; x < GameBorder; x++) {
output += outputBuffer[x][y];
}
output += "\n";
}
cout << output;
}
I am quite new to programming, and am trying to write a simple tic-tac-toe type game, with one human player (me) and one computer player.
I am currently writing a piece of the program as a void function that allows the human player to input 'X' into the specified array component. I'm using a character array of size [2][2] as my game board, and want the player to enter two numbers, e.g. 1 & 2, to specify their next move.
The following code is what I am using to create the 3x3 game board, and initialize each array component to '_'. Please ignore the aiMove function prototype, as I have not written anything for it yet.
#include <iostream>
using namespace std;
void playerMove(char[2][2]);
void aiMove(char[2][2]);
int col, row;
int main()
{
char ticTacToe[2][2];
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
ticTacToe[i][j] = '_'; //initializes all values of ticTacToe to '_'
cout << (ticTacToe[i][j]); outputs the starting board
}
cout << endl; // ends line after iterating through each row, creating a 3x3 board appearance
}
playerMove(ticTacToe);
return 0;
}
Below is the code where I am having the problem. I create the void function playerMove, and pass the ticTacToe array to the playerBoard array. I ask the player to pick two numbers, and input those into col and row, respectively. Using the do...while loop, I ensure that they player can only enter 0, 1 and 2 for the values of col and row. I then use the values of col and row to input an 'X' into the [col][row] element of the array.
Now that part works, as in I can get an X to go where I want it to go. However, after inputting one value, the program crashes with the debug error message:
Run-time check failure #2 - S.
I've done some research, and I think I know what is happening. By using the values of col and row to place the 'X' into the [col][row] element, I am inadvertently creating a situation where the playerBoard array could possibly go out of bounds. This is why I created the variables c and r, to see if by passing the values of col and row to these variables, I could effectively separate playerBoard from col and row. This didn't work.
So my two main questions are:
1) Am I understanding the error message correctly, e.g. does the problem lie with using col and row to place an 'X' into that array element, or is there something else I am missing?
2) How do I fix this error/re-write the code so it doesn't happen? I need the player to be able to select a particular array element where the column value is 0-2 and the row value is 0-2, while also inputting an 'X' into this array element.
I hope my questions are clear! This is my first post on Stack Overflow, and I tried very hard to follow guidelines and write a clear question, so please go easy!
void playerMove(char playerBoard[2][2])
{
char move = 'X';
int c = 0, r = 0;
do
{
cout << "Enter 2 numbers, 0-2, separated by a space. " << endl
<< "The first number is the column you wish to place your move " << endl
<< "and the second number is the row you wish to place your move. " << endl;
cin >> col >> row;
} while (((col >= 0 && col <= 2) && (row >= 0 && row <= 2)) == false);
c = col;
r = row;
playerBoard[c][r] = move;
for (int i = 0; i <= 2; i++)
{
for (int j = 0; j <= 2; j++)
{
cout << playerBoard[i][j];
}
cout << endl;
}
I'm having problems with creating a 2D boolean array in C++. I wrote a quick program for create and print all the bool array.
#include <iostream>
using namespace std;
int main() {
const int WIDTH = 20;
const int HEIGHT = 20;
bool world [HEIGHT][WIDTH];
for(int i = 0; i < HEIGHT; i++){
for(int j = 0; j < WIDTH; j++){
world[i][j] = true;
}
}
for(int i = 0; i < HEIGHT; i++){
for(int j = 0; j < WIDTH; j++){
if(world[i][j]){
cout << j;
}else{
cout << ' ';
};
}
cout << "-" << i << endl;
}
return 0;
}
And this is his output.
012345678910111213141516171819-0
012345678910111213141516171819-1
012345678910111213141516171819-2
012345678910111213141516171819-3
012345678910111213141516171819-4
012345678910111213141516171819-5
012345678910111213141516171819-6
012345678910111213141516171819-7
012345678910111213141516171819-8
012345678910111213141516171819-9
012345678910111213141516171819-10
012345678910111213141516171819-11
012345678910111213141516171819-12
012345678910111213141516171819-13
012345678910111213141516171819-14
012345678910111213141516171819-15
012345678910111213141516171819-16
012345678910111213141516171819-17
012345678910111213141516171819-18
012345678910111213141516171819-19
It creates a 2D array, set all his values to true, and print the array. This is fine, the problem is when the 2d array get bigger. For example if I change the size of WIDTH and HEIGHT to 30, when i print the array I have the following ouput:
01234567891011121314151617181920212223242526272829-0
01234567891011121314151617181920212223242526272829-1
01234567891011121314151617181920212223242526272829-2
01234567891011121314151617181920212223242526272829-3
01234567891011121314151617181920212223242526272829-4
01234567891011121314151617181920212223242526272829-5
01234567891011121314151617181920212223242526272829-6
01234567891011121314151617181920212223242526272829-7
01234567891011121314151617181920212223242526272829-8
01234567891011121314151617181920212223242526272829-9
01234567891011121314151617181920212223242526272829-10
01234567891011121314151617181920212201234567891011121314151617181920212223242526272829-11
01234567891011121314151617181920212223242526272829-12
01234567891011121314151617181920212223242526272829-13
01234567891011121314151617181920212223242526272829-14
01234567891011121314151617181920212223242526272829-15
01234567891011121314151617181920212223242526272829-16
01234567891011121314151617181920212223242526272829-17
01234567891011121314151617181920212223242526272829-18
01234567891011121314151617181920212223242526272829-19
01234567891011121314151617181920212223242526272829-20
01234567891011121314151617181920212223242526272829-21
01234567891011121314151617181920212223242526272829-22
01234567891011121314151617181920212223242526272829-23
01234567891011121314151617181920212223242526272829-24
01234567891011121314151617181920212223242526272829-25
01234567891011121314151617181920212223242526272829-26
01234567891011121314151617181920212223242526272829-27
01234567891011121314151617181920212223242526272829-28
01234567891011121314151617181920212223242526272829-29
As you can see on the line 11 it counts until 22 and restart the for loop for j. I don't know what is wrong, I need an 2D array of bools of size [50][50] but I don't what is wrong there.
EDIT: The problem is the compiler. I tried the same code on GCC compiler on a Linux machine and works perfectly. This code works fine, the problem is the compiler or the compiler with the CLion IDE. It compiles but I have problems with the running or the output produced. The code works fine with GCC compiler or on an Unix machine
Okay this is logically absolutely correct and i have tested your code on online compiler using 20 as well as 30. restart your compiler or try another compiler a reliable one... Here is the screenshot of your result when i executed your code online.
The line
bool world [WIDTH][HEIGHT];
Should be
bool world [HEIGHT][WIDTH];
As the i in your loop ranges from 0 to HEIGHT-1. j ranges from 0 to WIDTH-1
I did try many modifications to my code to make like this, but i not get what i want :
example if i put 7 in variable N the result will show
*
**
* *
* *
* *
* *
*******
this my code
#include <iostream>
using namespace std;
int main() {
for (int x=1; x<=N; x++){
cout<<"*";
for (int y=1; y<x; y++){
cout<<"*";
}
cout<<"\n";
}
return 0;
}
what i must add to my code have to the result like above?
Since others have suggested that this might be homework, here are some tips:
Always make sure you have a valid main signature. int main() is sufficient and main() without a return type is invalid.
Enable warnings. -Wall -pedantic should be sufficient for most cases (i.e, it catches the above mistake) but -Wextra can be useful as well.
using namespace std; is considered bad practice because you may define functions or variable names that clash with imported names. Get into the habit of typing std::. (For example, an assignment may require you to have a distance function, which may conflict with std::distance.
Use descriptive variable names. For a trivial program, x, y and N are fine, but decrease readability. It also helps you visualize the problem you are trying to solve.
We know that y is always going to be at most x because the number of characters per line should equal the current line. For example, line 7 should contain 7 asterisks. We only print a space if y is not equal to zero or x - 1, because that should be our "border". Lastly, the final line should contain all asterisks.
// The amount of asterisks per line is [1, N]
for (int x = 1; x <= N; x++)
{
// x is the amount of characters we want to print per line
for (int y = 0; y < x; y++)
{
// If we at the beginning or end of a line, this is our "border".
// Print an asterisk.
if (y == 0 || (y + 1 == x))
std::cout << "*";
else
{
// Otherwise we are "inside" the triangle.
// If this is the last line, print all asterisks
if (x == N)
std::cout << "*";
else
std::cout << " ";
}
}
std::cout << "\n";
}
Also, as another answer suggested, you can eliminate the need for confusing if structures by putting your condition into a single variable.
bool space_or_asterisk = (y == 0 || (y + 1 == x) || x == N);
std::cout << (space_or_asterisk ? '*' : ' ');
While you've gotten a couple of answers that work, the logic can be quite a bit simpler if you eliminate the confusing if/then/else statements:
#include <iostream>
int main() {
static const char chars[] = "* ";
static const int size = 7;
for (int i=0; i<size; i++) {
for (int j=0; j<size; j++)
std::cout << chars[j!=0 && i!=j && bool(i+1-size)];
std::cout << "\n";
}
}
Although the logic is clearly simpler, you still want to be sure to study it enough to answer any questions about it if you turn this in as homework.
main() {
for (int x=1; x<=N; x++){
for (int y=1; y<=x; y++){
if(y==1||y==x||x==N){
cout<<"*";
}else{
cout<<"*";
}
}
cout<<"\n";
}
return 0;
}
My question is much like this one Setting a value in a 2d array causes others in array to change, however it does not solve what I have here.
I am also trying to make a game field with a 2D array, currently full of '#'. I am trying to get the top left corner to become '.' (but leaving a border or '#' around the field, so its 1, not [0][0]).
However, whatever I tried so far always turns two spots into '.':
################.###
#.##################
####################
#####D##############
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
This doesn't make any sense, since (as far as I can see) I am not overflowing anywhere into a RAM slot, and even when I set map[1][1].symbol = '.'; it still gives those two spots as '.', though there is only one location being changed.
Code (partial):
#include <ctime>
#include "stdlib.h"
// Create structure for map tiles
struct mapTile{
char symbol;
bool walkable;
};
//Set map Width and Height and create empty array
//I did it like this so I can change the width and height later via ingame menu
int const mapWidth = 20;
int const mapHeight = 15;
mapTile map[mapWidth][mapHeight];
char x = 1;
char y = 1;
void generateField(){
srand(time(NULL)); //not used yet
//Set whole field to '#'
for(int y = 0; y < mapHeight; y++){
for(int x=0; x < mapWidth; x++){
map[y][x].symbol = '#';
map[y][x].walkable = false;
}
}
//Open up route to walk
map[3][5].symbol = 'D';
map[y][x].symbol = '.';
map[y][x].walkable = true;
};
void printField(){
//print each symbol of the field
for(int y = 0; y < mapHeight; y++){
for(int x=0; x < mapWidth; x++){
cout << map[y][x].symbol;
}
cout << endl;
}
}
In both your for-loops you access the map as [height][width], however you define it as [width][height].
Changing it solves the problem (on my machine).
first of all you are going out of the bounds of the array. The limit of your array is [mapWidth][mapHeight]. But in the initialization loop you are iterating the [y][x] - y till mapHeight and x till mapWidth.
And the second reason is, the value of x and y has already changed when you are initializing it to '.' and false. Please see the array size and work accordingly.