qsort() calling explanation

Hello,
I was reading about the pointers to functions and as an example my book has the qsort() algorithm. (this is the example of qsort() from this site:)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* 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;
}


can somebody plz explain me what exactly the following code does?
And what is this return exactly?
1
2
3
4
int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}


Thank you.
The (int*)a and (int*)a are casting the passed in parameters to integer pointers, and then the outer * dereferences that so *(int*)a - *(int*)b means value stored in memory pointed to by a minus the value stored in memory pointed to by b. The result of this calculation is returned to the calling function. In this case, qsort() uses it to decide how to order values.
Topic archived. No new replies allowed.