[英]cmpfunc in qsort() function in c
Can someone explain me cmpfunc
which is used in the qsort
function? 有人可以解释一下
qsort
函数中使用的cmpfunc
吗? What are a
and b
in this function and what are they pointing to? 此函数中的
a
和b
是什么,它们指向什么?
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
中的a
和b
是指向const void
类型的指针。 cmpfunc
can accept pointer to elements of array of any data type. cmpfunc
可以接受任何数据类型的数组元素的指针。
void *
pointer can't be dereferenced, therefore a cast int *
is needed before dereferencing. void *
指针无法取消引用,因此在取消引用之前需要强制转换为int *
。
In this inputs are *void and you need to comaper integers in your case. 在这种输入是*无效 ,你需要comaper整数你的情况。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.