GATE / CS ARCHIVE

GATE CSE 2019 / QUESTION 53

Value subtraction versus pointer subtraction

Programming in C · Pointers & Memory · Full GATE CSE 2019 paper

GATE 2019, Q53 2 marks · NAT
Report issue

Pointers & Memory

Question 53, GATE 2019: In C, a={2,4,6,8,10}, sum=0, and int *b=a+4. For i=0 through 4, execute sum=sum+(*b-i)-*(b-i); then print sum as an integer. What is printed?
Tap to enlarge
Answer & solution

Official answer: 10

Step through it (24 steps)

1. Pointer b is initialized to the final array element a[4]. No statement changes b, so *b remains 10 throughout the loop.
2. Distinguish the two expressions carefully. (*b-i) subtracts i from the value 10. By contrast, *(b-i) first moves the pointer i array positions backward and then reads a[4-i]. Pointer arithmetic counts int elements, not bytes.
3. For i=0,1,2,3,4, the first expression takes values 10,9,8,7,6. The second reads 10,8,6,4,2. Their differences are therefore 0,1,2,3,4.
4. Starting from zero, sum accumulates 0+1+2+3+4=10. Equivalently, a[4-i]=10−2i, so each summand is (10−i)−(10−2i)=i.
5. The output is 10 followed by a newline. All dereferences stay within a[0] through a[4]. The minus sign is subtraction, not a decrement of b, and confusing these operations would produce a different trace.

Original paper, page 16 · Answer key