我看到很多人在qsort比较函数中使用减法。我认为这是错误的,因为当处理这些数字时:int nums[]={-2147483648,1,2,3}; INT_MIN = -2147483648;
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
我写了这个函数来进行测试:
#include <stdio.h>
#include <limits.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main(void)
{
int a = 1;
int b = INT_MIN;
printf("%d %d\n", a,b);
printf("%d\n",compare((void *)&a,(void *)&b));
return 0;
}
输出结果为:
1 -2147483648
-2147483647
但是
a > b
,因此输出应为正数。我看过很多书籍都是这样写的,但我认为这是错误的;在处理int
类型时应该这样写:int compare (const void * a, const void * b)
{
if(*(int *)a < *(int *)b)
return -1;
else if(*(int *)a > *(int *)b)
return 1;
else
return 0;
}
我就是想不通为什么很多书籍和网站都用这种具有误导性的方式写作。如果您有不同的看法,请告诉我。
qsort()
与什么有关?信号整数溢出是未定义行为,你期望什么?还有一个INT_MAX
和1 + INT_MIN
溢出。 - Stargateur1 - (-INT_MIN) == 1 + INT_MIN
- Stargateur