简体   繁体   中英

cmpfunc in qsort() function in c

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);
}

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.

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; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM