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?
- A. return strcmp(*(char **)a, *(char **)b);
- B. return strcmp(a, b) > 0;
- C. return strcmp(a, b);
- 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
- int f(int n) { return n < 2 ? 1 : f(n - 1) + f(n - 2); } How many calls to f happen in total, counting the first call, when evaluating f(5)?
- A recursive Tower of Hanoi solution moves n disks, one at a time, with the rule that a larger disk never sits on a smaller one. How many…
- The Ackermann function is defined as A(0,n) = n+1, A(m,0) = A(m-1,1), and A(m,n) = A(m-1, A(m,n-1)) for m, n > 0. What is A(2,3)?
- int a[5] = {10, 20, 30, 40, 50}; int p = a + 1, q = a + 4; printf("%td %d", q - p, (p + 2)); prints what?
- void f(int a[10]) { printf("%zu", sizeof a); } Which statement about the result is correct?
- int m[2][3] = {{1, 2, 3}, {4, 5, 6}}; int (p)[3] = m; printf("%d", ((p + 1) + 2)); prints what?