Question

Consider the following program in C language:

#include <stdio.h>
main()
{
    int i;
    int *pi = &i;
    scanf("%d", pi);
    printf("%d\n", i + 5);
}

Which one of the following statements is TRUE?

Choose one option
Official answer and solution
Official answer
D
From
Official GATE 2014 answer key

Solution

Trace pointer initialization and argument passing to scanf in C.

In the program:

  • int i; declares an integer variable i.
  • int *pi = &i; initializes pointer pi to the address of i.
  • scanf("%d", pi); expects a pointer to an integer where the input should be stored. Since pi points to i, this correctly reads user input and stores it into i.
  • printf("%d\n", i + 5); outputs the value stored in i plus 5.

All operations are completely valid standard C code. Therefore, upon execution, the value printed is 5 more than the integer value entered (Statement D).

Final answer

D

Common trap

Mistakenly thinking scanf requires &pi, which would be an error since pi is already an int*.

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

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 1
Question
20 of 65, printed as CS Q.10
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.