简体   繁体   中英

My program crashes, I don't understand why it does not even reach the first printf

My program is supposed to order a list of numbers inputed by the user, but it crashes even before reaching the first printf. My compiler makes 2 warnings, but I don't see the issue. I haven't studied pointers yet, so I didn't want to use them. Here are the messages:

In function `selection_sort':

[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast 

In function `main':

[Warning] passing arg 2 of `selection_sort' makes pointer from integer without a cast 

.

#include<stdio.h>

int selection_sort(int n, int v[n])
{
    int high = v[0];
    int i;

    for(i = 0; i < n; i++)
        high = high < v[i]? v[i] : high;

    if(n - 1 == 0)
        return;

     v[n - 1] = high;
     n -= 1;

     selection_sort(n, v[n]);
}   



int main(void)
{   
    int n, i;
    int v[n];

    printf("Enter how many numbers are to be sorted: ");
    scanf("%d", &n);

    printf("Enter numbers to be sorted: ");
    for(i = 0; i < n; i++)
        scanf("%d", &v[i]);

    selection_sort(n, v[n]);

    printf("In crescent order: ");
    for(i = 0; i < n; i++)
        printf("%d ", v[i]);

    getch();
    return 0; 
}

Your program is using a variable length array, a feature that was added in C99.

However, you declare its size based on an uninitialized variable. What did you believe would happen there?

In C, variables declared inside functions are NOT set to 0. They are not set to anything. They pick up whatever value was left on the stack or in the register that they are assigned.

I believe that your program is crashing because n in int v[n] is a ridiculously big number and v is trying to use too much memory.

You can probably fix this by moving your array declaration below the scanf that reads in n .

You need to pass v , not v[n] to the function selection_sort. v is the array, v[n] is actually an out of bounds element of v .

the line should be selection_sort(n, v);

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