Why when we use qsort(), int(*compar)(const void*,const void*)
haven't add any paraments in, but can also do their functions?
Such as this :
double vals[NUM];
qsort(vals,NUM,sizeof(double),mycomp);
Why when we use qsort(), int(*compar)(const void*,const void*)
haven't add any paraments in, but can also do their functions?
Such as this :
double vals[NUM];
qsort(vals,NUM,sizeof(double),mycomp);
When you append parenthesis to the identifier representing a function, with a list of parameters between, you're calling the function.
In this case, you don't want to call the function, however. You want qsort
to call the function to determine whether or not one element is larger or smaller than the other.
It seems you are asking about function pointers in general.
Here is a simple example of function pointer:
int compare(int i, int j)
{
return i > j ? i : j;
}
void process(int i, int j, int(*pfunc)(int, int))
{
printf("%d\n", pfunc(i, j));
}
int main(void)
{
process(1, 2, compare);
return 0;
}
In this example process
is sort of like qsort
, while compare
is the function which we define ourselves. We need to tell qsort
how to compare data, but we can't access qsort
directly, so pass our own function to it which tells qsort
how to compare.
qsort
is generic. It doesn't know what type of data it is processing, so it can't simply compare elements using <
. What it does instead is let you, the programmer, give it a function to use to compare elements. So, yes you do care about how mycomp
works, you need to define it.
int mycomp(const void *a, const void *b) {
const double *lhs = a;
const double *rhs = b;
if (*lhs < *rhs) return -1;
if (*lhs > *rhs) return 1;
return 0;
}
inside of qsort
, every time it needs to compare two elements it will pass them to your mycomp
function and examine the result. If you define it wrong, your array will be incorrectly arranged (unsorted).