Reputation: 223
I'm attempting to use qsort() to sort an array of mine, but coming up with a weird error...
error: passing argument 4 of ‘qsort’ from incompatible pointer type
/usr/include/stdlib.h:761: note: expected ‘__compar_fn_t’ but argument is of
type ‘int (*)(struct Record *, struct Record *)’
Here is my function call:
qsort(arr, (sizeof(arr)/sizeof(struct Record)), sizeof(struct Record), compare);
And here is my compare method:
int compare (struct Record *a, struct Record *b){
return (a->key - b->key);
}
I know this is likely a casting issue - but I thought I could just pass the name of the comparative function itself..?
Upvotes: 0
Views: 1150
Reputation: 584
If you look, the error is quite clear: __compar_fn_t
has type int(*)(const void*, const void*)
but your function is int(*)(struct Record*, struct Record*)
. Quicksort doesn't know about the type of your array, so you have to use void*
for your comparator arguments and then cast them to the appropriate types inside it:
int compare (const void *a, const void *b){
struct Record const* a_r = (struct Record const*)a,
* b_r = (struct Record const*)b;
return (a_r->key - b_r->key);
}
Upvotes: 2
Reputation: 2898
int compare (const void * a, const void * b)
{
return ( *(struct Record*)a - *(struct Record*)b );
}
Upvotes: 1