ProgrammingVery hard

An array struct P *ps[] of pointers to records is to be sorted by an int field k with qsort. Which comparator is correct?

  1. A. int cmp(const void *a, const void *b) { int x = (*(struct P *const *)a)->k, y = (*(struct P *const *)b)->k; return (x > y) - (x < y); }
  2. B. int cmp(const void *a, const void *b) { return ((struct P *)a)->k - ((struct P *)b)->k; }
  3. C. int cmp(const void *a, const void *b) { return *(struct P *const *)a - *(struct P *const *)b; }
  4. D. int cmp(const void *a, const void *b) { int x = (*(struct P *const *)a)->k; return x; }

Correct answer: A. int cmp(const void *a, const void *b) { int x = (*(struct P *const *)a)->k, y = (*(struct P *const *)b)->k; return (x > y) - (x < y); }

qsort passes the address of each element, which is a pointer to a struct P pointer. One dereference gives the struct pointer, and -> reaches the key. The other versions treat the slot as the struct, subtract pointers, or ignore the second element.

More C Programming questions

Exams that ask this topic