简体   繁体   中英

Sorting array in C using function, but program just doesn't run

#include <stdio.h>
#include <conio.h>

void sorter(int b, int a[]);

int main(void){
    int i, j, arraySize;
    int arrayNums[arraySize];

    printf("Please enter how many numbers you wish to enter: ");
    scanf("%d", &arraySize);

    for(i =0; i<arraySize; i++)
    {
        printf("Enter Value No. %d: ", i+1);
        scanf("\n%d", &arrayNums[i]);
    }

    for(i=0; i<arraySize; i++)
    printf("%d", arrayNums[i]);

    sorter(arraySize,arrayNums);

    printf("after sorting");

    for(i=0; i<arraySize; i++)
    {
        printf("\n%d", arrayNums[i]);
    }
}

void sorter(int b, int a[]){
    int i,j, swap;

    for(i = 0; i<b; i++)
        for(j=i; j<b; j++)
        {
            if(a[i]>a[j]){
                swap= a[i];
                a[i]=a[j];
                a[j]=swap;
            }
        }
}

when I compile it in CodeBlocks, it gives:

Process terminated with status 0 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

and when I run the program, it just crashes.

Any clues?

The problem is :- you are using arraySize without initializing it.

I've just swaped two statements and it works fine.:-

     printf("Please enter how many numbers you wish to enter: ");
     scanf("%d", &arraySize);

     int arrayNums[arraySize];

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