0
votes

I have a problem compiling a program that uses 'qsort' I have to sort a dynamic array of pointers to a struct (called Element) when I try to compile the program I get the following error: "error: passing argument 4 of 'qsort' from incompatible pointer type..."

my compare function (for qsort) is:

int compareElements(const void **e1, const void **e2)
{
    Elemenet* element1 = *(Element** const)e1;
    Elemenet* element2 = *(Element** const)e2;
    if (element1->key < element2->key)
        return -1;
    ...................
}

Can anyone say what's wrong please.. ? I've tried so many patterns of altering that compare function and still nothing

Thank you

1
try int compareElements(const void *e1, const void *e2) - BLUEPIXY
@user3051798 Use BLUEPIXY's function declaration, and then cast the pointer to your desired type within the function. - user12205
"Can anyone say what's wrong please.. ? I've tried so many patterns of altering that compare function and still nothing" -- Did you try reading the documentation? The qsort manual entry gives the signature of the comparison function: int cmp(const void *a, const void *b) ... yours doesn't have that signature. - Jim Balter
@SergioFormiggini "If element->key is an integer, a float, a double or a char I think you may use the code: return element1->key - element2->key ;) " -- if you're fond of erroneous results due to overflow. - Jim Balter
@SergioFormiggini Not just unsigned ... int - int can result in undefined behavior. This matters when sorting arrays of arbitrary ints that can differ by more than can fit in an int. - Jim Balter

1 Answers

1
votes

this is the official prototype for the qsort function.

void qsort(void *base, 
          size_t nmemb, 
          size_t size,
          int (*compar)(const void *, const void *));

so the compare function prototype must be:

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

what those two const void* parameters are actually pointing to depends on what is being sorted.

for a 2 dimensional array, where the first index is an array of pointers

Then the const void* will be those pointers.

So the compare function will have to cast the parameters to what is actually being pointed to. Then perform the compare on what ever field is to be sorted on.

The return code +1, 0,-1 have exactly the same meaning as the return code from strcmp()