Ashley
Ashley

Reputation: 27

Qsort compare function

void qsort (void* base, size_t num, size_t size,
    int (*compare)(const void*,const void*));

Why does the qsort function want an int* return type for compare when the compare function is of type int?

int compare (const void * a, const void * b)
{
    if ( *(MyType*)a <  *(MyType*)b ) return -1;
    if ( *(MyType*)a == *(MyType*)b ) return 0;
    if ( *(MyType*)a >  *(MyType*)b ) return 1;
}

Can someone explain this please, my program wont compile because of this. Thanks! Code taken from this source: http://www.cplusplus.com/reference/cstdlib/qsort/

Upvotes: 1

Views: 684

Answers (1)

cdhowie
cdhowie

Reputation: 168988

It is not returning an int *, it is returning an int. compare is a function pointer. The * you are seeing there defines it as a function pointer. (Note the parentheses around *compare.)

cdecl parse of int (*compare)(const void*,const void*)):

declare compare as pointer to function (pointer to const void, pointer to const void) returning int

This would be the parameter declaration if it were a pointer to a function returning an int *:

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

If your code is not compiling then it is for some other reason. Consider adding the error message to your question (or creating a new question) if you would like more specific advice about the compiler error.

Upvotes: 3

Related Questions