C:qsort似乎不适用于unsigned long

Fre*_*ong 2 c unsigned qsort

谁能告诉我以下示例有什么问题?我把它从这里拿走并换成intunsigned long.我也改变了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);
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

Before sorting the list is: 
88 56 100 2 25 
After sorting the list is: 
25 2 100 56 88 
Run Code Online (Sandbox Code Playgroud)

250*_*501 8

你的比较功能不正确.无符号值的减法可以包含给出不正确结果的值.

该函数应该只比较值:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)