gpt4 book ai didi

c - C 中二维数组的错误初始化

转载 作者:行者123 更新时间:2023-11-30 14:49:13 27 4
gpt4 key购买 nike

我正在尝试为作业构造一个二维数组。我使用嵌套 for 循环使用 scanf() 构造二维数组:

  int width;
int height;

scanf("%d %d",&width,&height);

int array[width][height];

for (int i=0;i<height;i++){
for (int j=0;j<width;j++){
scanf("%d",&array[i][j]);
}
}

但是,当我打印数组时,我可以看到它是以一种奇怪的方式构造的,其中第一行经过某个点的所有数字都是第二行的前几个数字(而不是它们应该的数字)是)。工作正常后的下一行。

示例:

输入:

6 2

1 3 5 7 9 1

2 4 6 8 0 2

3 4 2 0 1 3

创建的数组如下所示:

1 3 2 4 6 8(<-- 最后 4 个数字是第二行的前 4 个数字)

2 4 6 8 0 2(正确)

3 4 2 0 1 3(正确)

有什么想法吗?非常感谢。

最佳答案

您的数组声明

int array[width][height];

是错误的。外层循环从0到height - 1,但是array[i]只能走从 0 到 width - 1。这同样适用于内循环。您交换了宽度和数组声明中的 height ,它应该是

int array[height][width];

另请注意,对于矩阵

1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3

宽度为6,高度为3,所以正确的输入应该是

6 3
1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3

我编译并运行了这段代码:

#include <stdio.h>

int main(void)
{
int width;
int height;

scanf("%d %d",&width,&height);

int array[height][width];

for (int i=0;i<height;i++){
for (int j=0;j<width;j++){
scanf("%d",&array[i][j]);
}
}

printf("----------------\n");

for (int i=0;i<height;i++){
for (int j=0;j<width;j++){
printf("%d ", array[i][j]);
}
printf("\n");
}


}

输出是:

$ ./b 
6 3
1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3
----------------
1 3 5 7 9 1
2 4 6 8 0 2
3 4 2 0 1 3

如您所见,现在它可以正确读取。请参阅https://ideone.com/OJjj0Y

关于c - C 中二维数组的错误初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49807234/

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