ProgrammingHard

Given char *names[] holding strings, which qsort comparator sorts them alphabetically?

  1. A. int cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }
  2. B. int cmp(const void *a, const void *b) { return strcmp((const char *)a, (const char *)b); }
  3. C. int cmp(const void *a, const void *b) { return *(char *)a - *(char *)b; }
  4. D. int cmp(const void *a, const void *b) { return strcmp(a, b); }

Correct answer: A. int cmp(const void *a, const void *b) { return strcmp(*(char *const *)a, *(char *const *)b); }

qsort passes pointers to the array elements, which here are char pointers. The comparator must dereference once before calling strcmp. The other versions compare the slots' addresses or single bytes.

More C Programming questions

Exams that ask this topic