I am currently learning about the qsort function, and I encountered the compare function:
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
I don't understand why we are using *(int*)a
. What is this thing, and what is its use? Why const void *a
instead of simple int a
?
答案 0 :(得分:3)
Since qsort is supposed to be able to sort an array of any kind of things (including structs), it passes (as arguments to its compare method) a pointer to each of the things to compare. These can be anything, so the type used is "void *" which can be a pointer to anything. Your compare method then should cast that pointer to a pointer of the correct type ( in this example, int *
because you are comparing two ints. then you dereference that cast pointer in order to compare the values pointed to, hence the *(int *)
答案 1 :(得分:1)
The (int*) do a typecast to the memory address of the variable 'a' that was before a void pointer. The * before (int*) access the integer value of the memory address. void *a is used because this is a generic function, you could use it to compare two char, for example.
答案 2 :(得分:0)
Your code is functionally equivalent to this:
int cmpfunc(const int* a, const int* b)
{
return(*a - *b);
}
In other words, (int*)a
casts your void* a
into an integer pointer type.