C stdlib qsort对指向结构的指针数组进行排序

C stdlib qsort对指向结构的指针数组进行排序,c,arrays,sorting,struct,qsort,C,Arrays,Sorting,Struct,Qsort,我试图根据存储在“bucket”结构的void*中的值,对指向结构(定义如下)的指针数组进行排序,我知道这些指针是int。它编译并打印出我的bucket数组及其值,没有错误或警告,但实际上并没有对数组进行排序。我使用断言尝试查找可能导致qsort错误的任何地方 结构定义: typedef struct _bucket{ void* val; char *word; }bucket; typedef struct _root{ bucket **list; int has

我试图根据存储在“bucket”结构的void*中的值,对指向结构(定义如下)的指针数组进行排序,我知道这些指针是int。它编译并打印出我的bucket数组及其值,没有错误或警告,但实际上并没有对数组进行排序。我使用断言尝试查找可能导致qsort错误的任何地方

结构定义:

typedef struct _bucket{
   void* val;
   char *word;
}bucket;

typedef struct _root{
   bucket **list;
   int hashTableLength;
}root;
要传递给qsort函数的排序函数:

int sortFunc(const void *a, const void *b){
   bucket *bucketA=(bucket*)a;
   bucket *bucketB=(bucket*)b;
   int bucketAVal = *((int*)bucketA->val);
   int bucketBVal = *((int*)bucketB->val);
   assert((bucketAVal&&bucketBVal)!=0);
   return bucketAVal-bucketBVal;
}
对阵列排序并打印:

void sort(root* inRoot, int(*sortFunc)(const void *a, const void *b)){
   int length = inRoot->hashTableLength;
   assert(length==11); //known length of hash array
   for (int i = 0; i<length; i++)
      assert(inRoot->list[i] != NULL);
   qsort(inRoot->list, length, sizeof(bucket*), sortFunc);
   for(int i =0; i<length; i++)
      printf("%s was found %d times\n", inRoot->list[i]->word, *((int*)(inRoot->list[i]->val)));
   return;
}
void排序(根*inRoot,int(*sortFunc)(常量void*a,常量void*b)){
int length=inRoot->hashTableLength;
assert(length==11);//哈希数组的已知长度
for(int i=0;ilist[i]!=NULL);
qsort(inRoot->list,length,sizeof(bucket*),sortFunc);
对于(inti=0;ilist[i]>word,*((int*)(inRoot->list[i]>val));
返回;
}

比较函数
sortFunc()
接收指向每个对象的指针。数组
inRoot->list
是一个
bucket*
数组,因此
sortFunc()
正在接收指向
bucket*
的指针:
bucket**

此外,
int
减法可能会溢出。使用惯用语2来解决这个问题

int sortFunc(const void *a, const void *b) {
  bucket **bucketA = (bucket**) a;
  bucket **bucketB = (bucket**) b;
  void *vA = (*bucketA)->val;
  void *vB = (*bucketB)->val;
  int iA = *((int*) vA);
  int iB = *((int*) vB);
  return (iA > iB) - (iA < iB);
}
int-sortFunc(常量无效*a,常量无效*b){
桶**桶塔=(桶**)a;
桶**桶b=(桶**)b;
void*vA=(*bucketA)->val;
void*vB=(*bucketB)->val;
int iA=*((int*)vA);
int-iB=*((int*)vB);
返回(iA>iB)-(iA