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] = 1
  • arr[1] = 2
  • arr[2] = 3
  • arr[3] = 4
  • arr[4] = 5
  • arr[5] = 6
  • arr[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):

ip[1]=∗(arr+4+1)=∗(arr+5)=arr[5]\text{ip}[1] = *(\text{arr} + 4 + 1) = *(\text{arr} + 5) = \text{arr}[5]

The value of arr[5] is 66. Therefore, printf displays 66.

Final answer

6

Common trap

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.