在 gcc
上测试 VLA 的非常简单的代码在 gcc-4.2.9 (Raspbian) 上运行良好,但在 gcc-6.2.0 (Ubuntu) 上运行不佳。我很惊讶。虽然编译没有错误,但输出不正确。
代码:
int len, i;
int test[len];
scanf("%d",&len);
for(i=0;i<=len;i++){
test[i]=i*i;
printf("%d\t",test[i]);}
printf("\n");
return 0;
参数:
8
输出:
使用 4.2.9(Raspbian),
0 1 4 9 16 25 36 49 64
使用 6.2.0 (Ubuntu),
0 1 4 9 16 1
连8都没有数到。我很惊讶。如果我对 len
的值进行硬编码,则相同的代码可以工作。
0 1 4 9 16 25 36 49 64
知道可能出了什么问题吗?
最佳答案
int len, i;
int test[len];
你正在做test[len]
,但此时len
尚未初始化。从未初始化的变量读取具有未定义的行为。
要解决此问题,请初始化 len
使用前:
if (scanf("%d",&len) != 1) {
// handle error
}
int test[len];
在其余代码中,使用 i<len
而不是i<=len
因为否则你会访问 len+1
元素仅 len
存在。
关于c - VLA 适用于 gcc-4.9.2,但不适用于 gcc-6.2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41912023/