3.2Pointer arithmetic
The idea
Pointer arithmetic counts in elements, not bytes. p + 1 is the next element of whatever p points to.
Think of it like this: Moving along a row of identical lockers: "next locker" means the next one, whatever its width in centimetres.
Why it exists
Array indexing is pointer arithmetic: a[i] is *(a + i). Pointer differences give element counts.
How it works
- p + k: address + k × sizeof(*p).
- p − q (same array): (address difference) ÷ sizeof(*p), an element count.
- p[i] is exactly *(p + i).
- You may compare two pointers into the same array, but never add them.
Worked example: p = a + 1, then *(p + 2) and p − a
With a = {10,20,30,40,50,60}: p points to 20. *(p + 2) is a[3] = 40. p − a = 1 element.
Now play with it
- →In the lab, try *(p + 2), p[3] and &a[4] − &a[1].
- →Watch the blue box move to the element a pointer result refers to.
p points to a[1]. Each expression below is a different way to name an element. Pointer arithmetic counts in ELEMENTS.
Memory (one box per element, address below)
Gold = the object the expression names. Blue = the element a pointer result points to. Each box stands for one element; real addresses grow by sizeof(element).
Check yourself
If int *p holds address 1000 and sizeof(int) is 4, what is the address of p + 3?
Exam notes (the dense version)
p + k moves by k elements, not k bytes: the address changes by k · sizeof(*p). p − q (same array) gives the number of elements between them, of type ptrdiff_t. You can compare pointers into one array, and p[i] is exactly *(p + i), so i[p] also works. Adding two pointers is illegal.
Previous year questions: Pointers & Arrays (11)
PYQs are grouped by topic, so this is the full set for Pointers & Arrays; try the ones that match this subtopic. Open all 11 on the topic page.