简体   繁体   中英

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..

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? To quote the initial part of that post:

C programs are executed from top to bottom. You can't declare a VLA with an uninitialized variable as its size parameter. 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 . Because it is already too late - I took input after I printed.

Similarly, int array[size]; doesn't create some magic bond between array and size . The array gets created to be as large as the value that size had at the point where that source code line was encountered. If size is uninitialized, then you get undefined behavior. Changing size afterwards does not change the size of the VLA. And you can't resize a VLA either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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