Reputation: 13
I am trying to initialise a 2D Array in C filled with X's except for the index (2,2) which will be filled with the letter 'C'. However, when I run the code below, not only do I get a 'C' at (2,2) but for some reason, I also end up getting a 'C' at the index (1,9) (see output below).
I tried changing the width and height values and realised that it works sometimes. For example, when I make height = 10 and width = 10, I get the correct output with only one 'C' in its proper slot.
I'm quite new to C programming and have no idea why it's producing the correct output sometimes. Any help would be much appreciated!
int width = 10;
int height = 7;
int x = 2;
int y =2;
int limit = 3;
//initialising 2D array
char board[width][height];
for(int i = 0; i < height; i++){//rows
for (int j = 0; j < width; j++){//cols
if(i == y && j == x){
board[y][x] = 'C';
}
else{
board[i][j] = 'X';
}
}
}
//printing 2D array
for(int i = 0; i < height; i++){//rows
for (int j = 0; j < width; j++){//cols
printf("%c ", board[i][j]);
}
printf("\n");
}
Upvotes: 1
Views: 704
Reputation: 20252
You got the array declaration wrong. Instead of
char board[width][height];
you need
char board[height][width];
/* Rows Cols */
Upvotes: 2