我在网上找到了这个示例代码,它解释了该qsort函数的工作原理.我无法理解比较函数返回的内容.
#include "stdlib.h"
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b) //what is it returning?
{
return ( *(int*)a - *(int*)b ); //What is a and b?
}
int main(int argc, _TCHAR* argv[])
{
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
int cmpfunc (const void * a, const void * b) //what is it returning?
{
return ( *(int*)a - *(int*)b ); //What is a and b?
}
Run Code Online (Sandbox Code Playgroud)
相当于:
int cmpfunc (const void * a, const void * b) //what is it returning?
{
// qsort() passes in `void*` types because it can't know the actual types being sorted
// convert those pointers to pointers to int and deref them to get the actual int values
int val1 = *(int*)a;
int val2 = *(int*)b;
// qsort() expects the comparison function to return:
//
// a negative result if val1 < val2
// 0 if val1 == val2
// a positive result if val1 > val2
return ( val1 - val2 );
}
Run Code Online (Sandbox Code Playgroud)
Whata和bare 在文档中明确说明qsort:这些是指向必须比较的数组元素的指针。
这种情况下的比较函数知道数组元素的类型int。因此它将void *指针转换为int *type 并int通过从第一个中减去第二个来执行指向值的三态比较。
它适用于您的一组值,但在一般情况下,使用减法进行三态比较是一种糟糕的编程实践,因为它容易溢出。此外,示例代码中的函数不必要地抛弃了指向值的常量性。
更好的选择是
int cmpfunc(const void *a, const void *b)
{
const int *A = a, *B = b;
return (*A > *B) - (*A < *B);
}
Run Code Online (Sandbox Code Playgroud)