1

文字のグリッドを作成しようとしています。この例では、3x3 グリッドを使用しています。文字の別の 1 次元配列から割り当てるために 2 つの 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);
    }
}
4

2 に答える 2

2

これらの 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  
于 2013-09-13T21:11:11.420 に答える
2

最初の行にエラーがあります

char text[8] = "abcdefghi"; 

サイズ 8 の配列を宣言しますが、それを 10 文字で初期化したいとします。これまたは次のいずれかを実行します。

char text[10] = "abcdefghi"; 

char text[] = "abcdefghi"; 

同様のエラーはchar grid[2][2];、3 x 3 ではなく 2 x 2 のグリッドがある場合にも発生します。

于 2013-09-13T21:11:36.310 に答える