Diogo Redin
Diogo Redin

Reputation: 69

qSort to sort structures

I'm trying to sort the following structure:

typedef struct thing {
    char *text;
    int count;
} *Item;

I'm creating an additional vector to sort the structures like this:

Item items[nr_of_items];

... here is a loop to place the items inside the vector items ...

qsort(items, nr_of_items, sizeof(Item), cmpItem);

And here is the compare function:

int cmpItem(const void *a, const void *b) {

  const Item item_a = (const Item)a;
  const Item item_b = (const Item)b;

  /* Return 1 or -1 if members are not equal */
  if (item_a->count > item_b->count) return 1;
  if (item_a->count < item_b->count) return -1;

  /* Return 1 or -1 if members are not equal */
  if ( strcmp ( item_a->text, item_b->text ) > 0 ) return 1;
  if ( strcmp ( item_a->text, item_b->text ) < 0 ) return -1;

  /* Return 0 if both members are equal in both structures */
  return 0;

}

The vector is being correctly created, however it isn't being sorted. Am I doing something wrong? Any help is appreciated.

Upvotes: 0

Views: 59

Answers (1)

fluter
fluter

Reputation: 13796

The compar callback function of qsort receive two arguments that point to the objects being compared, that is pointers to two elements in the items array. That means, both a and b are pointers to Item, not Item itself. You need change to this:

const Item *pa = a;
const Item *pb = b;
const Item item_a = *pa;
const Item item_b = *pb;

Upvotes: 3

Related Questions