ProgrammingHardTCS NQT · Infosys
char *words[] holds strings and must be sorted by length first and then alphabetically using qsort. Which comparator is correct?
- A. return strlen(*(char **)a) - strlen(*(char **)b);
- B. return strcmp(*(char **)a, *(char **)b);
- 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);
- 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
- char buf[4]; int n = snprintf(buf, sizeof buf, "%d", 12345); What is n?
- uint8t x = 0xB7; uint8t y = x | (x + 1); What is y?
- The number of ways to tile a 2 x 6 board with 2 x 1 dominoes equals the number of binary tilings given by T(n) = T(n-1) + T(n-2) with T(1)…
- Intervals (1,4), (2,3) and (3,5) are stored as pairs in an array and qsort sorts them ascending by their second value. Which pair comes…
- Which of these statements are well defined by the C standard? I. uint8t x = 255; x = x + 1; leaves x equal to 0. II. int a = INTMAX; a + 1…
- What is the sum of the decimal digits of 2^20 = 1048576?