CKTIS / C
Pointer arithmetic in C
Move pointers in element-sized steps, use the one-past position safely, and compute signed differences that fit in `ptrdiff_t`.
Version: ISO C23; implementation support may vary
Syntax
ISO C23 (implementation support may vary):
T *p; // T is a complete object type
p + n; n + p; p - n; // n has integer type; result has p's type
p += n; p -= n; // update a modifiable pointer variable
p - q; // compatible complete pointed-to types, possibly differently qualified; result: ptrdiff_tIn C, pointer arithmetic moves a pointer p to a complete object type by an integer number of elements, not bytes. p + n and n + p shift it by n positions; p - n shifts it in the opposite direction. The result keeps p's type, and p += n stores the new position in p. You cannot add two pointers. Arithmetic on void * or function pointers is a GNU C extension, not ISO C23.
The starting pointer and the result must each refer to an element of the same array during its lifetime or to the position just past its last element. You can use that one-past position as an end marker or step back from it, but you must not dereference it. Even forming a position before the first element or beyond one-past has undefined behavior. For these operators, an object that is not an array element behaves like a one-element array.
p - q requires pointers to compatible complete object types, which may differ in qualification. Both must belong to the same array in the sense above. The result is the signed difference of their indices in elements, with type ptrdiff_t from <stddef.h>. If it does not fit, the behavior is undefined. Use %td in printf. By contrast, + and - with two arithmetic operands perform numeric operations with the usual arithmetic conversions; unary - negates a number, not a pointer.
Before cur += lf or w += seg, handle any NULL error result and check the offset against the remaining array range. A non-null pointer alone proves neither validity nor bounds. When computing a byte size, check count <= SIZE_MAX / sizeof *p before multiplying, with count of type size_t and SIZE_MAX from <stdint.h>. That check establishes neither array bounds nor whether cur - r fits in ptrdiff_t.
Examples
#include <stddef.h>
#include <stdio.h>
int main(void)
{
int a[] = {10, 20, 30, 40};
int *r = a;
int *cur = r;
size_t lf = 2;
cur += lf;
int *w = cur;
size_t seg = 2;
w += seg;
printf("%d %td %td %td %d\n", *cur, cur - r, w - r, r - w, *(w - 1));
return 0;
}
Result
30 2 4 -4 40
`cur` points to `30`, and `w` is one past the array. `cur - r`, `w - r`, and `r - w` give `2`, `4`, and `-4`, respectively. `*(w - 1)` reads `40` without dereferencing `w`.
Related lessons
- C · Lesson 81 · Advanced · Version: 3