Pointers & Memory · beginner · ~10 min

Pointer arithmetic

Move within an array and explain the one-past-the-end boundary.

Overview

Pointer arithmetic moves in elements of the pointed-to type. Use a small array to see where each increment goes. The goal is to recognize the valid range before writing a loop, not to memorize numeric addresses.

Core concepts

For int a[3], a + 1 points to the second int, regardless of how many bytes an int occupies. a[i] and *(a + i) access the same element for a valid index.

You may form a + 3, the one-past pointer, and compare it to pointers within this array. You may not dereference it or form a + 4. Subtraction is defined for pointers into the same array (including one-past), when the difference is representable in ptrdiff_t. It yields an element count, not a byte count. Do not subtract pointers to unrelated objects.

Lesson

Pointer arithmetic moves in elements of the pointed-to type. Use a small array to see where each increment goes. The goal is to recognize the valid range before writing a loop, not to memorize numeric addresses.

Code examples

#include <stdio.h>
#include <stddef.h>
int main(void) {
    int a[] = {10, 20, 30};
    int *end = a + 3;
    printf("%d %td\n", *(a + 1), end - a);
    return 0;
}

Expected output on a successful allocation, where applicable:

20 3

Line by line

a + 1 identifies the second element. end marks the boundary after the third element. Subtracting the start from this boundary gives three elements; the boundary itself is never read.

Practice tasks

  1. Draw the three elements and the one-past boundary.
  2. Complete Nth element.
  3. Solve Distance between pointers, including a negative distance.
  4. Explain why replacing *(a + 1) with *(a + 3) is invalid; do not run the invalid access.

Summary

Pointer offsets count elements. A one-past pointer is a boundary, not an element. Keep arithmetic and subtraction within one array and use ptrdiff_t for differences.

Practice with these exercises