简体   繁体   English

反向打印 Array = Segmentation fault (core dumped)

[英]Print reverse Array = Segmentation fault (core dumped)

Saw that the error may occur when you try to access empty memory but it seems like I definied my 'for loops' well so I'm pretty much stuck here..看到当您尝试访问空的 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]; doesn't make sense.没有意义。 For some reason this bug is surprisingly common.由于某种原因,这个错误出奇地普遍。 See this FAQ on Codidact: How to declare variable-length arrays correctly?请参阅有关 Codidact 的常见问题解答: How to declare variable-length arrays correctly? To quote the initial part of that post:引用该帖子的开头部分:

C programs are executed from top to bottom.从上到下执行了C个程序。 You can't declare a VLA with an uninitialized variable as its size parameter.您不能将未初始化的变量作为其大小参数来声明 VLA。 For the same reason at you can't do this:出于同样的原因,你不能这样做:

 int x; printf("%d\n",x); scanf("%d",&x);

If I type 5 as input to this program, then it doesn't magically go back and change the printf to print 5 .如果我输入5作为该程序的输入,那么它不会神奇地返回 go 并将printf更改为打印5 Because it is already too late - I took input after I printed.因为已经太晚了——我在打印接受了输入。

Similarly, int array[size];同样, int array[size]; doesn't create some magic bond between array and size .不会在arraysize之间创建一些神奇的联系。 The array gets created to be as large as the value that size had at the point where that source code line was encountered.该数组被创建为与size在遇到该源代码行时的值一样大。 If size is uninitialized, then you get undefined behavior.如果size未初始化,则会出现未定义的行为。 Changing size afterwards does not change the size of the VLA.之后更改size不会更改 VLA 的大小。 And you can't resize a VLA either.而且您也无法调整 VLA 的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM