【问题标题】:Why change the values of 2d Array in C Language?为什么要在 C 语言中更改二维数组的值?
【发布时间】: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 建议的那样简单地修复声明。
  • 空格消失了很奇怪。

标签: c arrays 2d


【解决方案1】:

你应该在 if 块中增加 count 变量。

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 2010-10-23
    • 2020-07-16
    • 2023-02-07
    • 2020-07-29
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多