ProgrammingHardTCS NQT · Infosys

char *words[] holds strings and must be sorted by length first and then alphabetically using qsort. Which comparator is correct?

  1. A. return strlen(*(char **)a) - strlen(*(char **)b);
  2. B. return strcmp(*(char **)a, *(char **)b);
  3. C. size_t la = strlen(*(char **)a), lb = strlen(*(char **)b); if (la != lb) return la < lb ? -1 : 1; return strcmp(*(char **)a, *(char **)b);
  4. D. return strlen(*(char **)b) < strlen(*(char **)a);

Correct answer: C. size_t la = strlen(*(char **)a), lb = strlen(*(char **)b); if (la != lb) return la < lb ? -1 : 1; return strcmp(*(char **)a, *(char **)b);

The third version returns a proper three-way result for lengths and only then compares strings. The first wraps because size_t subtraction is unsigned, the second ignores length, and the last returns only 0 or 1.

More C Programming questions

Exams that ask this topic