With int a[4] = {10, 20, 30, 40}; int *p = a; what does printf("%d", *(p + 2)); print?
Correct answer
D. 30, the third element of the array
12 views
D. 30, the third element of the array
12 views
Pointer arithmetic is scaled by the size of the pointed-to type, so p + 2 points two ints past the base, and the dereference yields a[2], which is 30. p + 2 is not two bytes ahead unless the element type were char. Because a[i] is defined as *(a + i), the expression could equally be written p[2], and both forms stay in bounds only while the offset is less than 4.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.