ProgrammingHard
A qsort comparator must sort records by name in descending order using strcmp on char name[16] fields. Which is correct?
- A. return strcmp(((const struct R2 *)b)->name, ((const struct R2 *)a)->name);
- B. return strcmp(((const struct R2 *)a)->name, ((const struct R2 *)b)->name);
- C. return strcmp(a, b);
- 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
- An array of 10^6 records of 100 bytes each must be sorted. Which approach is correct and fast enough?
- struct S { int id; int v; }; struct S a[4] = {{1,9},{2,8},{3,7},{4,6}}; struct S b[4]; memcpy(b, a, sizeof a); b[0].v = 0; printf("%d %d"…
- struct Grid { int cell[2][2]; }; struct Grid g1 = {{{1, 2}, {3, 4}}}; struct Grid g2 = g1; g2.cell[1][1] = 0; printf("%d", g1.cell[1][1])…
- Which is the correct way to count distinct keys in a sorted struct array a[0..n-1] (n >= 1) by key?
- A sorted array of records is searched for the first record whose key is at least x (a lower bound). Which loop is correct?
- An array of 2 x 10^5 records must be answered with 2 x 10^5 queries, each asking how many records have key <= q. Which approach is correct…