ProgrammingHardGATE CS · Campus placements

char *names[] holds char pointers to strings and must be sorted alphabetically with qsort(names, n, sizeof names[0], cmp). Which comparator is correct?

  1. A. return strcmp(*(char **)a, *(char **)b);
  2. B. return strcmp(a, b) > 0;
  3. C. return strcmp(a, b);
  4. D. return *(char *)a - *(char *)b;

Correct answer: A. return strcmp(*(char **)a, *(char **)b);

qsort passes pointers to the array elements, so a points to a char *. You must dereference once to reach the string. Casting the element pointer straight to char * compares the wrong bytes.

More C Programming questions

Exams that ask this topic