ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
void swap(int **a, int **b) {
    int *temp = *a;
    *a = *b;
    *b = temp;
}
int main() {
    int x = 1, y = 2;
    int *p = &x, *q = &y;
    swap(&p, &q);
    printf("%d %d", *p, *q);
}
  1. A. Compilation error: swap expects int**
  2. B. 2 1
  3. C. 1 2
  4. D. 0 0

Correct answer: B. 2 1

Passing &p and &q (pointers to the pointers) lets swap actually exchange what p and q themselves point at, by dereferencing a and b once to reach p and q's storage. After swap, p points at y (2) and q points at x (1).

More C Programming questions

Exams that ask this topic