Question

Consider the following function implemented in C:

void printxy(int x, int y) {
    int *ptr;
    x = 0;
    ptr = &x;
    y = *ptr;
    *ptr = 1;
    printf("%d, %d", x, y);
}

The output of invoking printxy(1, 1) is

Choose one option
Official answer and solution
Official answer
C
From
Official GATE 2017 answer key

Solution

Trace the pointer assignments and memory modifications step by step.

Trace the execution of printxy(1, 1):

  1. Parameters x and y are initialized to 1 (local copies passed by value).
  2. int *ptr;: Declares a local pointer variable ptr.
  3. x = 0;: The local variable x becomes 0.
  4. ptr = &x;: The pointer ptr now stores the address of local variable x.
  5. y = *ptr;: Dereferences ptr (value of x, which is 0) and assigns it to local variable y. Thus, y becomes 0.
  6. *ptr = 1;: Modifies the memory location pointed to by ptr (which is x) to 1. Thus, x becomes 1.
  7. printf("%d, %d", x, y);: Prints the current values of x (1) and y (0).

The printed output is 1, 0, corresponding to option C.

Final answer

C

Common trap

Assuming *ptr = 1 changes y because y had received *ptr earlier; y = *ptr copied the value, not the reference.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2017 Computer Science and Information Technology (CS) Session 2
Question
14 of 65, printed as CS Q.14
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.