这是我的代码的一部分:
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]);
但是当我编译并运行它时,我得到这个:
|, |
我做错了什么?
通过访问超出数组范围调用未定义行为。分配足够的元素或者使用正确的索引
前的例子: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]);
后者的例子:
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 */
应该是:
board[0][w-1] = 'a';
board[1][0] = '|';
或
board[0][width] = 'a';
board[1][0] = '|';