2

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);
}
Jens
  • 69,818
  • 15
  • 125
  • 179
user007
  • 88
  • 1
  • 9
  • They are the two elements being compared in your function. – Idos Jan 02 '16 at 10:52
  • `a` and `b` are pointer to the elements of array. – ameyCU Jan 02 '16 at 10:53
  • 1
    @Idos Nitpicking: "*They are the two elements ...*" They are *not* the two elements themselves to be compared, but referring to, pointing to the elements to be compared. – alk Jan 02 '16 at 11:07

2 Answers2

4

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.

haccks
  • 104,019
  • 25
  • 176
  • 264
3

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; 
}
Vinod
  • 300
  • 3
  • 18