ProgrammingVery hardTCS NQT · Accenture

What is printed? Each struct has an int a and an int b.

What is printed? Each struct has an int a and an int b.
#include <stdio.h>
#include <stdlib.h>
struct P { int a, b; };
int cmp(const void *x, const void *y) {
    const struct P *p = x, *q = y;
    if (p->a != q->a) return p->a - q->a;
    return q->b - p->b;
}
int main(void) {
    struct P v[] = {{2, 1}, {1, 9}, {2, 0}};
    qsort(v, 3, sizeof v[0], cmp);
    for (int i = 0; i < 3; i++) printf("%d %d ", v[i].a, v[i].b);
}
  1. A. 1 9 2 0 2 1
  2. B. 1 9 2 1 2 0
  3. C. 2 1 2 0 1 9
  4. D. 2 0 2 1 1 9

Correct answer: B. 1 9 2 1 2 0

The primary key a ascending gives (1, 9) first. Among the two rows with a = 2, the secondary key b descending puts (2, 1) before (2, 0).

More C Programming questions

Exams that ask this topic