ProgrammingHardTCS NQT · Wipro

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    int a[] = {5, 6, 7}, *p = a + 1;
    printf("%d", p[-1] + *p + p[1]);
}
  1. A. 20
  2. B. Compile error: a subscript cannot be negative
  3. C. Undefined: p[-1] reads before the array
  4. D. 18

Correct answer: D. 18

p[-1] means *(p - 1), which is a[0] because p points at a[1]; that stays inside the array, so it is legal and defined. The sum is 5 + 6 + 7 = 18, while 20 treats p[-1] as the last element, Python-style.

More C Programming questions

Exams that ask this topic