Multiple choice

int x[] = { 1, 4, 8, 5, 1, 4 }; int *ptr, y; ptr = x + 4; y = ptr - x; What is the value of y in the sample code given above?

    • 3
  1. 0

  2. 4

  3. 4 + sizeof( int )

  4. 4 * sizeof( int)

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

ptr is set to x+4 (address of 5th element, value 1). ptr-x gives the number of elements between the two pointers, not the byte difference. Since ptr is 4 elements ahead of x, ptr-x=4. Pointer arithmetic on array elements gives element count, not byte offset.