[英]Print reverse Array = Segmentation fault (core dumped)
看到当您尝试访问空的 memory 时可能会发生错误,但似乎我很好地定义了我的“for 循环”,所以我几乎被困在这里..
int main () {
int size, arr[size];
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter %d numbers: ", size);
for (int i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("In normal order: \n");
for (int j = 0; j < size; j++) {
printf("|%d|\n", arr[j]);
}
printf("In reverse order: ");
for (int k = size - 1; k >= 0; k--) {
printf("|%d|\n", arr[k]);
}
return 0;
}
int size, arr[size];
没有意义。 由于某种原因,这个错误出奇地普遍。 请参阅有关 Codidact 的常见问题解答: How to declare variable-length arrays correctly? 引用该帖子的开头部分:
从上到下执行了C个程序。 您不能将未初始化的变量作为其大小参数来声明 VLA。 出于同样的原因,你不能这样做:
int x; printf("%d\n",x); scanf("%d",&x);
如果我输入
5
作为该程序的输入,那么它不会神奇地返回 go 并将printf
更改为打印5
。 因为已经太晚了——我在打印后接受了输入。同样,
int array[size];
不会在array
和size
之间创建一些神奇的联系。 该数组被创建为与size
在遇到该源代码行时的值一样大。 如果size
未初始化,则会出现未定义的行为。 之后更改size
不会更改 VLA 的大小。 而且您也无法调整 VLA 的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.