【发布时间】:2014-12-04 00:23:39
【问题描述】:
我在网上找到了这个示例代码,它解释了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;
}
【问题讨论】:
-
它们是从数组
values中读取的整数。该函数返回a-b的值,如果a较小,则为< 0(负数),如果相等,则为0,或> 0(正数)如果 a 更大。 -
qsort 的比较函数(实际上是回调函数)返回与 strcmp() IE 完全相同的值。如果第一个项目小于第二个项目返回 -1 如果项目匹配返回 0 如果第一个项目大于第二个项目返回 1
-
@user3629249:注意不要测试特定值
-1或1:strcmp()(或传递给qsort()的比较函数)允许返回任何负数或正数这些情况的值。 -
这个比较函数不好,永远不要使用它。假设,你正在排序-1500000000和1500000000。减法的结果是-3000000000,在@987654336中无法表示@,因此行为未定义。更糟糕的是,生成代码的通常行为是将其包装为一个正数 1294967296,这完全破坏了排序。 See AnT's answer for the one that works correctly 和 this QA for what can happen if you use this comparison function