C Reference ยท Types and Literals
Pointer arithmetic in C
Reference for pointer arithmetic in C: adding integers, subtracting pointers, scaling by element size, one-past-the-end rules, and void pointer pitfalls.
When you add an integer to a pointer, C moves the pointer by that many elements, not that many bytes. If p is an int *, then p + 1 points to the next int, which is sizeof(int) bytes later. The compiler does the scaling for you.
This is why array indexing and pointer arithmetic are the same thing: a[i] is defined as *(a + i). You can also subtract two pointers into the same array to count the elements between them, and compare them to see which comes first.
int a[5] = {10, 20, 30, 40, 50}; int *p = a; printf("%d\n", *(p + 3)); /* 40 */
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
p + n p - n n + p /* pointer moved by n elements */ p - q /* ptrdiff_t: elements between */ p++ p-- ++p --p p += n p -= n p < q p <= q p > q p >= q p == q p != q
| Operation | Result type | Description |
|---|---|---|
pointer + integer |
same pointer type | Moves n * sizeof(*p) bytes forward. |
pointer - integer |
same pointer type | Moves backward. |
pointer - pointer |
ptrdiff_t |
Number of elements apart; both must point into the same array. |
| relational | int (0 or 1) |
Ordering within one array. |
Errors / undefined behavior: the result must stay inside the array or point one element past its end; anything else, even without dereferencing, is undefined. You may not dereference the one-past-the-end pointer. Subtracting or ordering pointers into different arrays is undefined. Comparing with == is fine for any pair of compatible pointers.
Usage notes
- No arithmetic on
void *in standard C. GCC allows it as an extension, treatingsizeof(void)as 1, but portable code casts tochar *first. - Never add two pointers. Only pointer plus integer and pointer minus pointer are allowed.
*p++means*(p++): the value is read, then the pointer advances.(*p)++increments the target instead.- Counting backwards is tricky:
p - 1before the start of an array is undefined, so the second example stops withbreakrather than stepping befored. - Pointers to different struct sizes step differently.
struct S *p; p + 1moves bysizeof(struct S), including padding. - Use
ptrdiff_tand%tdfor differences, notint. - Prefer indices when clarity matters. Optimizers treat both forms alike; use pointers when walking a buffer or parsing.
- Do not print the pointers. Differences are stable; absolute values are not.