Question
Consider the following C program:
#include <stdio.h>
int main(){
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5}, *ip = arr + 4;
printf("%d\n", ip[1]);
return 0;
}
The number that will be displayed on execution of the program is ___________.
Official answer and solution
- Official answer
- 6
- From
- Official GATE 2019 answer key
Solution
Trace pointer arithmetic and array indexing in C.
We are given the array:
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 5};
The element indices and values are:
arr[0] = 1arr[1] = 2arr[2] = 3arr[3] = 4arr[4] = 5arr[5] = 6arr[6] = 7
The pointer ip is initialized as:
int *ip = arr + 4;
Here, ip points to element arr[4] (value 5).
The expression ip[1] is equivalent by definition to *(ip + 1):
The value of arr[5] is . Therefore, printf displays .
6
Printing arr[4] (5) instead of arr[4 + 1] (6).
The answer is the one in the official GATE answer key. The solution is this site's own explanation.
Source
- Paper
- GATE 2019 Computer Science and Information Technology (CS)
- Question
- 34 of 65, printed as CS Q.24
- 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.