gpt4 book ai didi

c - scanf() 中的错误

转载 作者:行者123 更新时间:2023-11-30 15:57:31 27 4
gpt4 key购买 nike

首先,我的代码中有一个逻辑错误。嗯,这是代码

#include <stdio.h>

int main()
{
long i,j,t;
scanf("%ld",&t);
long n[t],d[t][t];
for(i = 0; i < t;i++){
scanf("%ld",&n[i]);
for(j = 0; j < n[i] ;j++){
scanf("%ld",&d[j][i]);
}
}
for(i = 0; i < t;i++){
for(j = 0; j < n[i] ;j++){
printf("%ld ",d[j][i]);
}
printf("\n");
}
return 0;
}

然后我输入数据

2
4
25 20 30 90
3
45 50 55

结果是

25 20 30 90
45 50 55

嗯,这正是我所期望的。然而,当输入变成这样

3
5
12 67 89 34 56
6
34 56 78 90 12 34
7
12 34 89 23 56 78 89

结果变成这样了

12 34 89 23 56 78 89
12 67 89 34 56 4206692 7 2293472 1982002386 16 3 2293344 2293408 0 2293552 0 0 4
198585 8918456 1982106837 1982010910 8918456 2293640 0 0 1985286516 2009576437 0
0 2293664 2009323341 2293740 2147348480 0
34 56 78 90 12 34 4199405 1982595752 8 12 2293424 2 2 1982356412 2147348480 2293
608 2147348480 1 -1 297753669 1982010784 1982015505 4199044 0 0 2147348480 21473
48480 0 0 0 7273647 2009576392 0 0 0 1 0 20 52 0 0 438759246 736 -214797894 1420
760826203 2272 852421325 3108 944791496 4028 -1322777276 4988 9 1 1 1204 7168 4
2 152 11832 7 1 40 12316 1682469715 1 140 44 0 0 0 2 0 7209065 5701724 6029427

12 34 89 23 56 78 89

好吧,简单的问题,为什么输出会变成上面这样?当我输入以上2时,会发生相同的结果。如果您不介意的话,有任何可能的答案和链接吗?谢谢

最佳答案

在很多情况下,您都在二维数组之外进行写入,有时您不会收到错误,但这只是偶然。

通过输入数组的数量来确定二维数组的大小,同时也确定内部数组的大小:

scanf("%ld",&t);
long n[t],d[t][t];

例如,让我们举第一个例子:

2              >> create array n[2], and array d[2][2]
4 >> number of values to d[0]
25 20 30 90 >> d[0][1] = 25 d[0][2] = 20 you access d[0][3] and d[0][4] but you are not allowed to do that.
3 >> number of values to d[1]
45 50 55 >> d[1][0] = 45 d[1][1] = 50 you access d[1][2] but you are not allowed to do that

关于c - scanf() 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10442752/

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