CodeMonkey
CodeMonkey

Reputation: 368

stdlib qsort to sort an array of pointers to a struct

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.

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:

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

Upvotes: 1

Views: 423

Answers (1)

chux
chux

Reputation: 153498

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

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

Upvotes: 2

Related Questions