Skip to content
Official PYQ · 2010

GATE CS 2010 Q11 — Programming in C

Explain with AI

What does the following program print?

#include<stdio.h>

void f(int *p, int *q) {
    p=q;
    *p=2;
}

int i=0, j=1;

int main() {
    f(&i, &j);
    printf("%d %d\n", i,j);
    return 0;
}
Choose one option
View worked solution

Answer: D

Let's trace the execution of the program step-by-step:

  1. Initialization: The global variables are initialized as:
    i = 0, j = 1
  2. Function Call: In main(), the function f(&i, &j) is called.
    • The local pointer p in f is initialized with the address of i (i.e., p = &i).
    • The local pointer q in f is initialized with the address of j (i.e., q = &j).
  3. Inside Function f:
    • p = q;: This reassigns the local pointer p to point to the same memory location as q. Now, p points to j (i.e., p = &j). Note that this change is local to f and does not affect the variable i.
    • *p = 2;: This dereferences p and modifies the value at that address. Since p now points to j, this statement updates the value of j to 2.
  4. Print Statement: After returning to main(), the values of the global variables are printed:
    • i remains unchanged: 0
    • j has been modified to: 2

Thus, the program prints 0 2.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Programming in C questions