What will the following C code print? int a[] = {1, 2, 3, 4}; int *p = a;…
2026
What will the following C code print?
int a[] = {1, 2, 3, 4};
int *p = a;
printf("%d", *(++p) + 2);Answer: B. 4 — Concept: In C, how the increment (++) and dereference (*) operators combine depends entirely on grouping and precedence, so the parentheses in *(++p) are…
- A.
3
- B.
4
- C.
5
- D.
Compilation error: invalid use of increment operator on pointer dereference
Attempted by 60 students.
Show answer & explanation
Correct answer: B
Concept: In C, how the increment (++) and dereference (*) operators combine depends entirely on grouping and precedence, so the parentheses in *(++p) are decisive: they make ++ apply to the pointer p, so p is pre-incremented to the next element first and only then is the new address dereferenced. Advancing a pointer moves it by sizeof(the pointed-to type), not by 1 byte. This differs from other groupings -- *p++ dereferences p's current address and advances p afterward (post-increment), and ++*p leaves p unchanged and instead increments the value it points to -- so the placement of the parentheses, not the mere presence of both operators, determines the result.
Application -- tracing the code step by step:
int a[] = {1, 2, 3, 4}; creates an array with a[0] = 1, a[1] = 2, a[2] = 3, a[3] = 4, stored in contiguous memory.
int *p = a; makes p an int pointer holding the address of a[0], so *p at this point would read 1.
In *(++p) + 2, the pre-increment ++p executes first: it advances p by one int-sized step, so p now holds the address of a[1].
The dereference *(...) then reads the value at the pointer's new position, a[1], which is 2.
Adding 2 gives 2 + 2 = 4, and printf("%d", 4); prints 4.
Cross-check: pointer arithmetic guarantees a + 1 is the address of a[1]; since p was initialized to a (i.e. the address of a[0]), the pre-increment ++p necessarily advances p to a + 1 = &a[1], so *(++p) reads a[1] = 2, matching the step-by-step trace, and 2 + 2 = 4.
Result: the program prints 4.