C: qsort 似乎不适用于 unsigned long

C: qsort doesn't seem to work with unsigned long

任何人都可以告诉我以下示例有什么问题吗?我从 here 中取出并用 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;
    }
}