How does pointer arithmetic work?
Short answer: Adding an integer n to a pointer moves it by n * sizeof(*p) bytes, so p + 1 points to the next element, not the next byte. Subtracting two pointers into the same array gives the number of elements between them (type ptrdiff_t). Arithmetic is only defined within one array object (and one past its end).
uint32_t buf[4] = {10, 20, 30, 40};
uint32_t *p = buf; /* &buf[0], say address 0x20000000 */
p + 1; /* 0x20000004 -> buf[1] */
*(p + 2); /* 30, same as p[2] */
(uint8_t *)p + 1; /* 0x20000001: one byte further */
uint32_t *end = buf + 4; /* one past the end: valid to compute and compare, not to dereference */
ptrdiff_t n = end - p; /* 4 elements, not 16 bytes */
Equivalences: p[i] is defined as *(p + i), so buf[2], *(buf + 2), p[2] and even 2[buf] are the same element.
Rules
- Only add/subtract integers to pointers, and subtract pointers that point into the same array. Adding two pointers is meaningless (and not allowed).
- Going beyond one-past-the-end, or before the start, is undefined behaviour even if you never dereference it.
void *arithmetic is not allowed in standard C (GCC treats it likechar *as an extension).- Comparing pointers with
</>is only defined within one array; comparing for equality is always fine.
Precedence with increment: *p++ reads *p then advances p; (*p)++ increments the value; *++p advances first then reads.
Embedded use: walking a received byte buffer, and computing register addresses: (volatile uint32_t *)(base + 0x14) where base is a uintptr_t, or &periph->CR with a struct overlay. Be careful: if base is a uint32_t *, then base + 0x14 moves by 0x14 * 4 = 0x50 bytes.