#include <stdio.h>
int main(void) {
int n,i;
int str[n];
scanf("%d\n",&n);
for(i=0;i<=n;i++)
{
scanf("%d",&str[i]);
printf("%d th %d\n",i,n);
}
return 0;
}
输入:
10
8 9 2 1 4 10 7 6 8 7
输出:
0 th 10
1 th 10
2 th 10
3 th 10
4 th 10
5 th 10
6 th 10
7 th 6
为什么输出6?
最佳答案
这确实是奇怪的代码,具有未定义的行为。您对此有何期望:
int n; // No value!
int str[n];
去做?您将得到一个长度未知的数组,因为
n
在str
声明点没有值。如果您希望编译器在
str[n]
赋予n
值时神奇地“时间旅行”回到scanf()
行,那么...那不是Co的工作方式,您应该认真阅读语言多一点。并编译所有可以从环境中获得的警告。作为一个额外的细节,即使已修复它以使
n
具有值,for
循环也会覆盖数组并再次为您提供未定义的行为。对于大小为
m
的数组,循环头应读取for (size_t i = 0; i < m; ++i)
由于索引是基于0的,因此无法在数组的外部
m
进行索引。