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

时间:2022-09-06 12:01:22

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.

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

Struct definitions:

结构定义:

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

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

Sort Function to be passed to the qsort function:

要传递给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;
}

Sort the array and print:

对数组进行排序并打印:

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

1 个解决方案

#1


2  

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 **.

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

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

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

#1


2  

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 **.

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

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

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