我正在尝试创建字符网格,在本例中我使用的是 3×3 网格。我正在使用两个 for 循环从一个单独的一维字符数组进行赋值,但每一行的最终值总是等于下一行的第一个值,但我不明白为什么。我计算行和列有问题吗?
char text[8] = "abcdefghi";
char grid[2][2];
int i,j;
for(i=0; i<=8; i++)
{
char c = text[i];
int row = i/3;
int col = i%3;
printf("%c row=%d col=%d i=%d\n", c, row, col, i);
grid[row][col] = c;
}
printf("------\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%c row=%d col=%d \n", grid[i][j], i, j);
}
}
最佳答案
改变这两个声明
char text[8] = "abcdefghi"; //you require size of 10
//9 bytes to store 9 characters and extra one is to store null character
char grid[2][2]; here you need to declare 3 by 3
// array[2][2] can able to store four characters only
// array[3][3] can store 9 characters
像这样
char text[10] = "abcdefghi"; //you require size of 10
char grid[3][3]; here you need to declare 3 by 3
关于c - 使用 for 循环的二维数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18795268/