KSH
KSH

Reputation: 35

Qsort of dynamically allocated array of numbers

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

int compare(const void *a, const void *b);

int main(void) {
    int input;    
    scanf("%d", &input);

    int* array = (int *) calloc(input, sizeof(int));

    for (int i = 0; i < input; i++) {
        scanf("%d", &array[i]);
    }

    qsort(array, sizeof(array)/sizeof(int), sizeof(int), compare);

    for (int i = 0; i < input; i++) printf("%d ", array[i]);

    return 0;
}

int compare(const void *a, const void *b)
{
    int num1 = *(int *)a;
    int num2 = *(int *)b;

    if (num1 < num2) return -1;
    if (num1 > num2) return 1;
    return 0;
}

I am still a student of C language basics. It might be a very basic question because you haven't learned it all right. I'm trying to sort a dynamic array. I created and sorted a dynamic array, but looking at the result, there is no sorting at all. What is the problem?

Upvotes: 0

Views: 65

Answers (1)

hookenz
hookenz

Reputation: 38907

The value for nitems (second parameter) passed to qsort is wrong.
Your program works if you change the qsort call to:

qsort(array, input, sizeof(int), compare);

sizeof can't be used on malloc'd memory the way you're doing it. It only works on fixed sized arrays like int array[10]. Because at compile time the compiler knows how many elements there are.

sizeof(array)/sizeof(int) // <= won't work.  is equivalent to
sizeof(int*) / sizeof(int)

The result is probably 1. So you're qsorting the first element only

Upvotes: 2

Related Questions