Pointer arithmetic forms a pointer by adding or subtracting an integer offset from a pointer into an array object. If a points to the first element, a + i points to element i, while a + len denotes the one-past position used as a stopping boundary. A pointer does not retain the array length, so functions receiving an array through a pointer must receive its length separately. section 11.1.2
double sum0(size_t len, double const* a) {
double ret = 0.0;
for (size_t i = 0; i < len; ++i) {
ret += *(a + i);
}
return ret;
}
This summation loop makes the equivalence between pointer addition and indexed array access explicit: *(a + i) accesses element i. section 11.1.2
Keep these validity rules in view:
- Increment or decrement pointers only within the boundaries of their array object, including the permitted one-past position; dereferencing that one-past position is not valid. section 15.1.1
- Subtracting an integer moves toward earlier elements; subtracting two pointers computes their distance in elements only when both point into the same array object. section 11.1.3
- Store pointer differences in ptrdiff_t rather than int, because the difference may not fit in an ordinary integer type. section 11.1.3
- Prefer A[i] over *(A + i) when expressing access to a particular element; indexing communicates intent and may make invalid indices easier for compilers to detect. section 15.1.1
Computing a position with pointer subtraction
For an array double A[4] = { 0.0, 1.0, 2.0, -3.0 }, pointers p = &A[1] and q = &A[3] satisfy p - q == -2. The result is the difference between their element indices, not a byte address difference. section 11.1.3


