liveBook · Manning

Pointer arithmetic

As explained in Modern C, Third Edition

Pointer arithmetic is the C operation of forming pointer values by adding or subtracting integer offsets relative to elements of an array object.

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

How Modern C, Third Edition covers it

How deep it goes
Defines addition, subtraction, one-past boundaries, same-array requirements, and ptrdiff_t, while deferring broader pointer mechanics.
Examples
Demonstrates forward and reverse summation, one-based subarray starts, infinite-element diagnostics, and same-array pointer differences.
What it assumes
Assumes familiarity with C arrays, pointers, dereferencing, function parameters, and integer types.
What you can do after
Apply it to traverse arrays, calculate element distances, and diagnose invalid pointer relationships without confusing pointers with arrays.
How it connects
Connects arrays, array indexing, pointer subtraction, size_t, ptrdiff_t, and undefined behavior from invalid array-bound operations.

Also explained in

Compare how 3 books explain pointer arithmetic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.