Pointer Arithmetic
Challenge Gallery
Quick Reference
Pointer arithmetic rules:
| Expression | Meaning |
|---|---|
p + n |
Address n elements past p |
p - n |
Address n elements before p |
p - q |
Number of elements between p and q |
p++ |
Advance p to next element |
*p++ |
Read *p, then advance p |
Equivalences:
arr[i] == *(arr + i) // Always true
&arr[i] == arr + i // Always true
Common Pitfalls
- Scaling confusion –
p + 1addssizeof(*p)bytes, not 1 byte. The compiler scales automatically. - Subtracting pointers to different arrays – Only valid for pointers into the same array. Otherwise: undefined behavior.
- Off-by-one with one-past-end – You can POINT to one-past-the-end but must NOT dereference it.
- *p++ precedence – It’s
*(p++), not(*p)++. Postfix ++ binds tighter than dereference.