gpt4 book ai didi

c - 二维数组不打印正确的输出

转载 作者:太空宇宙 更新时间:2023-11-04 02:31:23 25 4
gpt4 key购买 nike

我正在尝试用 X 填充 C 中的二维数组,但索引 (2,2) 将填充字母“C”。但是,当我运行下面的代码时,不仅在 (2,2) 处得到了一个“C”,而且出于某种原因,我最终还在索引 (1,9) 处得到了一个“C”(请参见下面的输出).

我尝试更改宽度和高度值并意识到它有时会起作用。例如,当我设置高度 = 10 和宽度 = 10 时,我得到的正确输出只有一个“C”位于其正确的位置。

我对 C 编程还很陌生,不知道为什么它有时会产生正确的输出。任何帮助将不胜感激!

int width = 10;
int height = 7;
int x = 2;
int y =2;
int limit = 3;

//initialising 2D array
char board[width][height];
for(int i = 0; i < height; i++){//rows
for (int j = 0; j < width; j++){//cols
if(i == y && j == x){
board[y][x] = 'C';
}
else{
board[i][j] = 'X';
}
}
}
//printing 2D array
for(int i = 0; i < height; i++){//rows
for (int j = 0; j < width; j++){//cols
printf("%c ", board[i][j]);
}
printf("\n");
}

Sample output

最佳答案

你的数组声明有误。而不是

char board[width][height];

你需要

char board[height][width];
/* Rows Cols */

关于c - 二维数组不打印正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com