Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of the following pseudocode?

int arr[] = {1, 2, 3, 4, 5}
int *ptr = arr + 2
print(*ptr + *(ptr + 1))

  • A.3
  • B.5
  • C.7
  • D.9

Answer: C

The output is 7.

The array holds 1, 2, 3, 4, 5 at indices 0 to 4. arr + 2 points to index 2, so *ptr is 3. ptr + 1 points to index 3, so *(ptr + 1) is 4. The sum is 3 + 4 = 7.

Pointer arithmetic moves by whole elements, not bytes, so arr + 2 is the third element. 5 is the sum of indices 1 and 2 (2 + 3), a slip of taking arr + 2 as the second element. 9 is 4 + 5, a slip of one position too far, and 3 is the first value alone.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.