首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对指向结构的指针数组进行排序的stdlib qsort

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

Stack Overflow用户
提问于 2015-02-01 01:22:56
回答 1查看 404关注 0票数 1

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

结构定义:

代码语言:javascript
复制
typedef struct _bucket{
   void* val;
   char *word;
}bucket;

typedef struct _root{
   bucket **list;
   int hashTableLength;
}root;

要传递给qsort函数的排序函数:

代码语言:javascript
复制
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;
}

对数组进行排序并打印:

代码语言:javascript
复制
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;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-01 02:17:07

比较函数sortFunc()接收指向每个对象的指针。数组inRoot->listbucket *的数组,因此sortFunc()接收指向bucket *bucket **的指针。

此外,int减法也会受到可能溢出的影响。用习语2比较解决这个问题。

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28258466

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档