【发布时间】:2018-06-11 15:21:16
【问题描述】:
这是我的简单代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int row = 2,col = 5;
//This my word array with new line character and ABCDE and FGHIJ
char hello[] = "ABCDE\nFGHIJ\n";
//Here i put these letters into 2d char array and print end print each elements
char grid[col][row];
int count = 0;
for(int i = 0; i<row;i++){
for(int j = 0; j<col;){
if(hello[count] != '\n'){
grid[i][j] = hello[count];
printf("%c ",grid[i][j]);
j++;
}
count++;
}
printf("\n");
}
puts("--------------------------------");
//Here i print each elements again
for(int p = 0; p<row;p++){
for(int q = 0; q<col;q++){
printf("%c ",grid[p][q]);
}
printf("\n");
}
return 0;
}
终于接受了
ABCDE
FGHIJ
但结果是
ABFGH
FGHIJ
出现这种现象的原因是什么。我的意图是将每个字母放入网格 2d 字符数组中。但是在我打印了其中的每个元素后,它显示错误。
【问题讨论】:
-
C 中的二维数组以行优先顺序存储。将
char grid[col][row];更改为char grid[row][col];。 -
是的,看起来您在寻址矩阵时正确排序了行/列,但在声明它时没有。应该像 jdc 建议的那样简单地修复声明。
-
空格消失了很奇怪。