问题
Code below taken from here.
* qsort example */
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
printf ("%d ",values[n]);
return 0;
}
We have a compare function with parameters in its signature but when we call it in qsort no arguments are passed. How are the values of a
and b
passed to the function? Thanks
回答1:
In the context of this expression:
qsort (values, 6, sizeof(int), compare);
the subexpression compare
that identifies a function decays into a pointer to that function (and not a function call). The code is effectively equivalent to:
qsort (values, 6, sizeof(int), &compare);
This is exactly the same thing that happens to arrays when used as arguments to a function (which you might or not have seen before but is more frequently asked):
void f( int * x );
int main() {
int array[10];
f( array ); // f( &array[0] )
}
回答2:
When calling qsort, you're passing a pointer to the function which is why you don't specify any parameters.
Inside the qsort implementation choses values from the 'values' array and calls the 'compare' function. That's how 'a' and 'b' get passed.
回答3:
qsort
passes the addresses of whichever items in the array it wants to compare. For example, &values[3]
and &values[5]
.
Since it doesn't really know the actual types of the items in the array, it uses the size
parameter to correctly compute the addresses. See this implementation for example: http://insanecoding.blogspot.ie/2007/03/quicksort.html
来源:https://stackoverflow.com/questions/11353260/why-dont-you-need-to-pass-arguments-to-a-qsort-comparator-function