Pointer arithmetic moves through an array by adding or subtracting integer offsets. If a points to an array element, a + i points to the element i positions later; the resulting pointer may also designate the position immediately beyond the array, but that position must not be dereferenced. TAKEAWAY: Pointers are not arrays. A pointer does not preserve the array length, so functions receiving an array through a pointer must receive its length separately. section 11.1.2 section 11.1.4
Walking an array with a pointer
double sum1(size_t len, double const* a) { double ret = 0.0; for (double const* p = a; p < a + len; ++p) { ret += *p; } return ret; } Here, p begins at a, advances one array element per iteration, and stops at a + len. The loop can form the one-past pointer, but it must stop before dereferencing it. section 11.1.2
Use pointer arithmetic according to these rules:
- Subtract an integer to traverse an array backward; summation order may consequently be reversed. section 11.1.3
- Subtract two pointers only when both refer to elements of the same array; the result is their difference in element positions and has type ptrdiff_t. section 11.1.3
- Do not dereference a one-past pointer, and do not add an offset that moves beyond the one-past position; those operations have undefined behavior. section 11.1.4
double A[7] = { 0, 1, 2, 3, 4, 5, 6, };
double s0_7 = sum0(7, &A[0]); // For the whole
double s1_6 = sum0(6, &A[1]); // For the last 6
double s2_3 = sum0(3, &A[2]); // For the 3 in the middle
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":0},{\"line\":1,\"ch\":6}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":6}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":6}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":0},{\"line\":1,\"ch\":6}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":6}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":6}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":0},{\"line\":1,\"ch\":6}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":6}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":6}],[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":0},{\"line\":1,\"ch\":6}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":6}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":6}]]"}
!@%STYLE%@!
Shows how the same summation function can receive the whole array or a subarray by pairing a starting element with an explicit length. section 11.1.2


