ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
#include <stdlib.h>
int cmp(const void *a, const void *b) {
    const int *x = *(int *const *)a;
    const int *y = *(int *const *)b;
    return (*y > *x) - (*y < *x);
}
int main(void) {
    int v0 = 7, v1 = 2, v2 = 9, v3 = 4;
    int *ptrs[] = {&v0, &v1, &v2, &v3};
    qsort(ptrs, 4, sizeof ptrs[0], cmp);
    for (int i = 0; i < 4; i++) printf("%d ", *ptrs[i]);
}
  1. A. 9 7 4 2
  2. B. 2 4 7 9
  3. C. 9 4 7 2
  4. D. 7 4 2 9

Correct answer: A. 9 7 4 2

The comparator receives pointers to elements that are themselves pointers, so it must dereference twice. It returns a positive value when *y is larger, which sorts the pointers in descending order of the values they point to.

More C Programming questions

Exams that ask this topic