cmpfunc in qsort() function in c

 ̄綄美尐妖づ 提交于 2019-12-25 03:45:27

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/34565028/cmpfunc-in-qsort-function-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!