问题
Can someone explain me cmpfunc
which is used in the qsort
function? What are a
and b
in this function and what are they pointing to?
int cmpfunc(const void *a, const void *b)
{
return(*(int*)a - *(int*)b);
}
回答1:
a
and b
in cmpfunc
are pointers to const void
type. cmpfunc
can accept pointer to elements of array of any data type.void *
pointer can't be dereferenced, therefore a cast int *
is needed before dereferencing.
回答2:
In this inputs are *void and you need to comaper integers in your case. So you will need to convert types. That's why there are
*(int *) a
it can be float type
*(float *) a
and so on other type...
you can find this implementation :
int cmpfunc(const void *a, const void *b)
{
if(*(int *)a < *(int *)b) return -1;
if(*(int *)a == *(int *)b) return 0;
if(*(int *)a > *(int *)b) return 1;
}
来源:https://stackoverflow.com/questions/34565028/cmpfunc-in-qsort-function-in-c