0
#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?

2
  • 2
    array is a pointer. So sizeof(array) is a size of the pointer. Commented Nov 11, 2020 at 19:53
  • You don't need fancy stuff like than when int input contains the number of elements to sort. Commented Nov 11, 2020 at 19:54

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Could also change sizeof(int) to sizeof array[0] to remove type dependencies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.