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);- A. 0
- B. 5, wrapping around to the last element
- C. Undefined behaviour: p[-1] accesses memory before the start of the array, which is out of bounds
- 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
- What happens when this runs? c int global; int main(void) { printf("%d", global); }
- What happens when this runs? c void fillBuffer(char buf, int size) { for (int i = 0; i <= size; i++) { buf[i] = 'A'; } } int main(void) {…
- What happens when this runs? c int a = 5; int b = a++ + a++ + a++; printf("%d %d", a, b);
- What happens when this runs? c struct Point { int x, y; }; struct Point p = malloc(sizeof(struct Point)); printf("%d", p->x);
- What happens when this runs? c char concat(const char a, const char b) { char result[100]; strcpy(result, a); strcat(result, b); return…
- What is printed? c int a = 5, b = 2, c = 3; int result = a > b > c; printf("%d", result);