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

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

结构定义:

typedef struct _bucket{ void* val; char *word; }bucket; typedef struct _root{ bucket **list; int hashTableLength; }root; 

要传递给qsort函数的Sort函数:

 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; ilist[i] != NULL); qsort(inRoot->list, length, sizeof(bucket*), sortFunc); for(int i =0; ilist[i]->word, *((int*)(inRoot->list[i]->val))); return; } 

比较函数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); }