ProgrammingHardHCL · Tech Mahindra pattern

What happens when this runs?

What happens when this runs?
int arr[5] = {1, 2, 3, 4, 5};
int *p = arr;
int val = p[-1];
printf("%d", val);
  1. A. 0
  2. B. 5, wrapping around to the last element
  3. C. Undefined behaviour: p[-1] accesses memory before the start of the array, which is out of bounds
  4. D. Compile-time error: negative array index

Correct answer: C. Undefined behaviour: p[-1] accesses memory before the start of the array, which is out of bounds

p[-1] is equivalent to *(p - 1), which computes and dereferences an address one element BEFORE arr[0] — entirely outside the array's valid memory. C performs no bounds checking and there is no wraparound semantics for arrays (unlike Python's negative indexing); this is undefined behaviour, reading whatever happens to sit in adjacent memory.

More C Programming questions

Exams that ask this topic