简体   繁体   中英

Question regarding allocating memory for array, sorting and numbers only in C programming

I have a program that I would like to dynamically allocate an array that gets filled by the user through the terminal argument line in Linux. After the user enters the numbers, the array of numbers should be sorted.

#include <stdio.h>
#include <stdlib.h>

int main(){

    int i;
    int array[100];
    int count = 0;
    while(1){
        printf("please enter a number: \n");
        scanf("%d", &i);
        if(i == 0){
            for (int k = 0; k < count -1; k++) {
                    if(array[k] <= array[k + 1]){
                    int temp = array[k];
                    array[k] = array[k+1];
                    array[k+1] = temp;
                }
            }
            for (int j = 0; j < count; ++j)
            {
                printf("%d ", array[j]);
            }
            printf("\n");
            break;
        } else {
                array[count] = i;
                count++;
        }
    }       
}

This only sorts the array if I type the numbers in low to high, but if I enter the numbers from high to low eg. 4, 3, 2 and then 1, it prints 2, 3, 1 and then 4, instead of the 1,2,3,4 that it does if I type it that way. I don't want to initialize the array with 100, I just can't get it to work if I don't initialize it. I want it to be increased if necessary.

Thank you :)

Errors/Deviations from the proposed program:

  • As mentioned, you want to use command line arguments - You need main(argc,*argv[]) instead of main() .
  • For dynamic allocation you need malloc/calloc but instead of that you have used static array.

  • Your code shows you are not clear about concept of sorting, leave the program aside and use a pen and paper first to clear that.

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