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?
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 variablei.int *pi = &i;initializes pointerpito the address ofi.scanf("%d", pi);expects a pointer to an integer where the input should be stored. Sincepipoints toi, this correctly reads user input and stores it intoi.printf("%d\n", i + 5);outputs the value stored iniplus 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).
D
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.