C/C++ Arena

Step 4 of 6

Sorting with qsort

The standard library's qsort can sort any array, because you hand it a comparator callback:

void qsort(void *base, size_t count, size_t size,
           int (*cmp)(const void *, const void *));

The comparator receives pointers to two elements (as const void *, which you convert back to the real type) and returns negative, zero or positive, like strcmp.

static int by_value(const void *pa, const void *pb) {
    int a = *(const int *)pa, b = *(const int *)pb;
    return (a > b) - (a < b);   // not a - b: that can overflow!
}

Your turn: write a comparator by_score_desc for Player structs: higher score first, and for equal scores, alphabetical by name. Then sort_players calls qsort with it.

Previous: A dispatch table Next: Generic code with void *