ProgrammingHard

A qsort comparator must sort records by name in descending order using strcmp on char name[16] fields. Which is correct?

  1. A. return strcmp(((const struct R2 *)b)->name, ((const struct R2 *)a)->name);
  2. B. return strcmp(((const struct R2 *)a)->name, ((const struct R2 *)b)->name);
  3. C. return strcmp(a, b);
  4. D. return -strcmp(b, a);

Correct answer: A. return strcmp(((const struct R2 *)b)->name, ((const struct R2 *)a)->name);

Swapping the arguments reverses the order. The other versions sort ascending or pass the void pointers straight to strcmp, which is a type error that the code cannot rely on.

More C Programming questions

Exams that ask this topic