我正在尝试根据存储在“桶”结构的void*中的值(下面的定义)对指向结构的指针数组进行排序,我知道这个值是ints。它编译并打印出我的存储桶数组及其值,没有任何错误或警告,但实际上它并没有对数组进行排序。我已经使用断言来尝试查找任何可能导致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;
}发布于 2015-02-01 02:17:07
比较函数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);
}https://stackoverflow.com/questions/28258466
复制相似问题