使用for循环分配2D数组

时间:2013-09-13 21:07:48

标签: c arrays for-loop multidimensional-array

我正在尝试创建一个字符网格,本例中我使用的是3by 3网格。我使用两个for循环从一个单独的一维字符数组中分配,但每行的最终值总是等于下一个的第一个值,但无法理解为什么。我对row和col的计算有问题吗?

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);
    }
}

2 个答案:

答案 0 :(得分:2)

更改这两个声明

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  

答案 1 :(得分:2)

第一行有错误

char text[8] = "abcdefghi"; 

您声明一个大小为8的数组,但是您想要用10个字符初始化它。做这个或这个:

char text[10] = "abcdefghi"; 

char text[] = "abcdefghi"; 

类似的错误是char grid[2][2];,你有2乘2格而不是3乘3。

相关问题