/ˈpɔɪntər ˌærɪθˈmɛtɪk/

noun … “Calculating addresses with pointers.”

Pointer Arithmetic is a programming technique that performs mathematical operations on pointers to navigate through memory locations. It allows programmers to traverse arrays, structures, and buffers by adding or subtracting integer offsets from a pointer, effectively moving the reference to different memory addresses. This technique is widely used in low-level languages like C and C++ for efficient memory access and manipulation.

Key characteristics of Pointer Arithmetic include:

  • Offset-based navigation: adding an integer to a pointer moves it forward by that many elements, taking the element size into account.
  • Subtraction and difference: subtracting pointers yields the number of elements between them.
  • Compatibility: typically applied to pointers referencing arrays or contiguous memory regions.
  • Risk of undefined behavior: incorrect arithmetic can access invalid memory or cause segmentation faults.
  • Integration with heap and stack allocations for dynamic and local data traversal.

Workflow example: Traversing an array using pointer arithmetic in C:

int array[5] = {10, 20, 30, 40, 50}
int* ptr = &array[0]
for int i = 0..4:
    printf("%d", *(ptr + i))  -- Access elements via pointer arithmetic

Here, adding i to ptr moves the pointer to successive elements of the array, allowing iteration without using array indices explicitly.

Conceptually, Pointer Arithmetic is like walking along a street of houses: each house has a fixed width, and moving forward or backward by a certain number of houses (offset) lands you at a predictable location.

See Pointer, Array, Heap, Stack, Memory.