232k views
4 votes
Consider the following C code fragment:

short arr[] = { 2, 4, 6, 8, 10, 12, 14, 16 };
short* p1 = arr + 10;
short* p2 = arr + 6;

Give the exact value of the following expression as an integer.

*(arr + (p1 - p2))

1 Answer

1 vote

Answer:

10

Step-by-step explanation:

Pointer arithmetic is tricky. The address is incremented by the sizeof the pointed element. A short is 2 bytes.

So adding 10 adds 20 bytes to the starting address of arr[].

In the expression, you're adding 10-6 = 4 to the start of the array, so you're pointing at the fifth element, arr[4] which is 10.

User Letoncse
by
5.0k points