pointers-memory · intermediate · ~15 min
Cast generic void pointers and implement multi-key tie-breaking for qsort.
The standard C qsort() function accepts a function pointer int (*cmp)(const void *, const void *). To sort complex structures, the comparator must cast the generic void* arguments and implement multi-level tie-breaking.
Implement:
struct employee {
int id;
int score;
char name[32];
};
int employee_cmp(const void *a, const void *b);
Sort employees:
score in descending order (highest score first).id in ascending order (lowest id first).score and id match, return 0.< 0 if a should precede b.> 0 if b should precede a.0 if a and b are considered equivalent.a, b: generic const void* pointers to struct employee instances.
Returns negative, zero, or positive integer for qsort.
C11 freestanding comparator. Cast void* safely.
#include <stddef.h>
/* The harness provides:
struct employee {
int id;
int score;
char name[32];
};
*/
int employee_cmp(const void *a, const void *b) {
(void)a; (void)b;
return 0;
}
Subtracting scores directly leading to signed integer overflow; sorting ascending instead of descending for score.
Identical scores tie-break on id; identical score and id return 0; negative scores.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.