Pointers & Memory
![Question 24, GATE 2019: A C program initializes int arr[]={1,2,3,4,5,6,7,8,9,0,1,2,5}; and int *ip=arr+4; then prints ip[1] using the %d conversion. Find the integer displayed.](../../assets/questions/CS-2019-Q34-1.webp)
Answer & solution
Official answer: 6
Method: identify the pointer's base element, then apply C's definition of the subscript operator.
1. C array indices start at zero. Thus arr[0]=1, arr[1]=2, arr[2]=3, arr[3]=4, arr[4]=5, and arr[5]=6. “Index 4” denotes the fifth element, not the fourth.
2. In the expression arr+4, arr converts to a pointer to its first element, &arr[0]. Adding 4 to an int pointer advances it by four int elements, not by four bytes. Therefore ip=&arr[4], pointing at the value 5.
3. For a pointer p, C defines p[k] as *(p+k). Consequently ip[1]=*(ip+1): advance one more int from arr[4], then read the value at that location.
4. Substitute the pointer value explicitly: *(ip+1)=*((arr+4)+1)=*(arr+5)=arr[5]=6.
5. The access stays within the 13-element array and does not modify either ip or arr. The %d conversion prints the selected integer, followed by the newline specified in the program.
Result: 6. ip[0] would be 5, whereas ip[1] is 6; ip[1] is not the same as arr[1] because the two indexing expressions use different base pointers. No assumption about the byte size of int is needed.