[英]C: qsort has a problem sorting unsigned long long members of a structure
[英]C: qsort doesn't seem to work with unsigned long
谁能告诉我以下示例有什么问题? 我从这里取出它并用unsigned long
替换int
。 我还更改了cmpfunc
以正确处理unsigned long
。
#include <stdio.h>
#include <stdlib.h>
unsigned long values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b)
{
if(*(unsigned long*)a - *(unsigned long*)b < 0){
return -1;
}
if(*(unsigned long*)a - *(unsigned long*)b > 0){
return 1;
}
if(*(unsigned long*)a - *(unsigned long*)b == 0){
return 0;
}
}
int main()
{
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ )
{
printf("%lu ", values[n]);
}
qsort(values, 5, sizeof(unsigned long), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ )
{
printf("%lu ", values[n]);
}
return(0);
}
这是我得到的输出:
Before sorting the list is:
88 56 100 2 25
After sorting the list is:
25 2 100 56 88
你的比较功能不正确。 无符号值的减法可以包含给出不正确结果的值。
该函数应该只比较值:
int compare( const void* a , const void* b )
{
const unsigned long ai = *( const unsigned long* )a;
const unsigned long bi = *( const unsigned long* )b;
if( ai < bi )
{
return -1;
}
else if( ai > bi )
{
return 1;
}
else
{
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.