GATE Computer ScienceHardGATE CS (PYQ pattern)

void g(int **pp, int *q, int k) { *q += k; *pp = q + 1; **pp += *q; q = *pp; *q -= k; } int main() { int a[3] = {1, 2, 3}; int *p = a; g(&p, p, 4); g(&p, p, 1); printf("%d %d %d %td", a[0], a[1], a[2], p - a); } What is printed?

  1. A. 6 8 3 1
  2. B. 5 4 6 2
  3. C. 5 8 11 2
  4. D. 5 4 7 2

Correct answer: B. 5 4 6 2

Call 1 (q = &a[0], k = 4): a[0] = 5; p becomes &a[1]; a[1] = 2 + 5 = 7; the local q now points to a[1], so a[1] = 7 - 4 = 3. Call 2 receives the updated p (q = &a[1], k = 1): a[1] = 4; p becomes &a[2]; a[2] = 3 + 4 = 7; then a[2] = 7 - 1 = 6. Reassigning the local q does not change the caller, but writing through it does. Output 5 4 6 2.

More Programming and Data Structures (GATE) questions

Exams that ask this topic