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

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

本文介绍了stdlib qsort对结构体的指针数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据存储在我知道是int的"bucket"结构的void *中的值对结构的指针数组(以下定义)进行排序.它编译并打印出我的存储桶数组,它们的值很好,没有错误或警告,但实际上并没有对该数组进行排序.我使用断言来尝试查找可能导致qsort错误的任何地方.

I am trying to sort an array of pointers to structs (definition below) based on the value stored in the void* of the "bucket" struct that I know are ints. It compiles and prints out my array of buckets and their values just fine with no errors or warnings but it isn't actually sorting the array. I have used asserts to try to find anywhere that could cause an error with qsort.

结构定义:

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

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

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

Sort Function to be passed to the qsort function:

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;
}

推荐答案

比较函数sortFunc()接收到每个对象的指针.数组inRoot->listbucket *的数组,因此sortFunc()正在接收到bucket *指针:bucket **.

The compare function sortFunc() receives a pointer to each object. The array inRoot->list is an array of bucket * so sortFunc() is receiving pointers to bucket *: bucket **.

此外,int减法可能会发生溢出.使用惯用的2比较来解决该问题.

Also the int subtraction is subject to possible overflow. Use the idiomatic 2 compares to solved that.

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);
}

这篇关于stdlib qsort对结构体的指针数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 01:19