c - 使用 for 循环的二维数组赋值

标签 c arrays for-loop multidimensional-array

我正在尝试创建字符网格,在本例中我使用的是 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/

相关文章:

Antlr C 解析器能否从无效 token 中恢复

javascript - 在输出上复制数组的函数

php - 获取 MySQL 表的列表并为每个表运行代码

python - 将字典作为嵌套附加到字典

c - 为结构体中的灵活数组分配内存

将 C 字符串逐个字符复制到动态 char*

C编程中对字符串的混淆

arrays - 如何创建带有随机数的数组?

php - 使用 PHP 将数组插入 MySQL 数据库

java - 我的 "for loops"-- Java 出现问题