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]);
}- A. 9 7 4 2
- B. 2 4 7 9
- C. 9 4 7 2
- 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
- What is printed? c #include <stdio.h> int main(void) { int m[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) m[i][j] = i 3…
- How many times is disk 3 moved in this recursive Towers of Hanoi with 5 disks? Compute the program output. c #include <stdio.h> int cnt =…
- How many integers n with 1 <= n <= 64 satisfy both (n & (n - 1)) == 0 and (n & 0x55555555u) != 0? Compute with this program. c #include…
- What is printed? c #include <stdio.h> int main(void) { int a[5]; int p = a + 4, q = a + 1; printf("%ld", (long)(p - q) (long)sizeof p); }
- What is printed? Assume int is 32 bits and integer division truncates toward zero. c #include <stdio.h> int main(void) { int v[] = {-7…
- What is the maximum value of depth printed? c #include <stdio.h> int depth = 0, maxd = 0; void r(int n) { depth++; if (depth > maxd) maxd…