Altern8 Altern8 - 3 months ago 6
C Question

Trying to create a 2D list but the first element of a row changes the last element of last row to the said element

This a part of my code:

int h = height+1;
int w = width+1;
char board[h][w];
board[0][w] = 'a';
board[1][0] = '|';

printf("%c, %c", board[0][w], board[1][0]);


but when i compile and run it i get this:

|, |


what am I doing wrong?

Answer

You invoked undefined behavior by accessing out-of-range of array. Allocate enough elements or use correct index.

former example:

int h = height+1;
int w = width+1;
char board[h][w+1]; /* allocate w+1 elements instead of w */
board[0][w] = 'a';
board[1][0] = '|';

printf("%c, %c", board[0][w], board[1][0]);

latter example:

int h = height+1;
int w = width+1;
char board[h][w];    
board[0][w-1] = 'a'; /* use w-1 instead of w */
board[1][0] = '|';

printf("%c, %c", board[0][w-1], board[1][0]); /* use w-1 instead of w */
Comments