Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 171 ยท Pointers, References and Memory

Pointers and Arrays

Learn C++ pointer arithmetic - how arrays decay to pointers, p + n and p[n], pointer differences, one-past-the-end, comparison rules and iterating with pointers.

Arrays and pointers are tightly linked in C++. An array's elements sit next to each other in memory, so once you have a pointer to one element, you can reach its neighbors by moving the pointer forward or backward. That movement is pointer arithmetic: p + 1 isn't "the address plus one byte", it's "the next element".

This is how C-style arrays really work under the hood, how a[i] is defined, and what iterators in the standard library are modeled on. You'll learn how arrays decay to pointers, what you may and may not do with p + n, why the "one-past-the-end" pointer is legal and useful, and which comparisons between pointers are well defined. Along the way you'll see why modern code prefers std::span, std::array and std::vector, which carry their size with them. Make sure you're comfortable with Pointers first.

Arrays decay to pointers

In almost every expression, the name of a C-style array turns into a pointer to its first element. This conversion is called array-to-pointer decay. It's why you can write int* p = numbers; without an &.

C++ An array name becomes a pointer to element 0

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Decay does not happen with sizeof, with &numbers (which gives a pointer to the whole array, type int (*)[5]), when binding a reference to the array, or with decltype. Everywhere else, including when you pass the array to a function, you get a plain int*, and the size is lost. That's the root of the classic bug covered in C-Style Arrays: inside a function taking int values[], sizeof(values) is the size of a pointer.

Pointer arithmetic: moving between elements

Adding an integer n to a pointer moves it n elements, not n bytes. The compiler multiplies by sizeof the element type for you. Subtracting works the same way backward, and ++/-- step one element.

C++ Stepping through an array with p + n

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Since a double is 8 bytes, readings + 1 is 8 bytes further along. (Converting a pointer to the integer type std::uintptr_t is the safe way to look at raw byte addresses, purely for demonstration.)

a[i] is *(a + i)

The subscript operator is defined in terms of pointer arithmetic: a[i] means *(a + i). That's why p[3] works on a pointer and why p[-1] is fine when p points into the middle of an array. It also explains a famous oddity: because a + i == i + a, the expression 2[numbers] is legal and means numbers[2]. Never write that, but now you know why it compiles.

Watch the precedence when combining * and ++:

Expression Meaning
*p++ use *p, then move p forward (postfix ++ binds tighter)
(*p)++ increment the element p points to
*++p move p forward, then use the new element
++*p increment the element p points to

*p++ is a classic C idiom for "read and advance". In C++ you'll mostly use range-based for or algorithms instead, but you'll see it in older code.

Iterating with pointers

A pointer to the first element and a pointer one past the last element describe a whole array. Loop while the current pointer is not equal to the end pointer:

C++ Looping from begin to end with pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

This half-open range [begin, end) is exactly the design of the standard library: v.begin() and v.end() on any container, and algorithms like std::sort(first, last). Pointers into an array are iterators, the most powerful kind (random-access, contiguous), so every standard algorithm works on them directly. std::begin(values) and std::end(values) give you these two pointers for a C array, and std::size(values) gives the count (it only works where the array hasn't decayed).

Half-open ranges have nice properties: the number of elements is end - begin, an empty range is just begin == end, and splitting a range at mid gives [begin, mid) and [mid, end) without any +1/-1 fiddling.

The one-past-the-end rule

You may form a pointer to any element of an array and to the position just past the last element. That one extra position exists so loops like the one above have something to compare against. But it comes with strict limits:

C++
int a[3]{1, 2, 3};
int* end = a + 3;   // OK: one past the end, a valid pointer value
int x = *end;       // UNDEFINED: there is no element there
int* beyond = a + 4;  // UNDEFINED: just computing it is not allowed
int* before = a - 1;  // UNDEFINED: there's no "one before the beginning"

The rules, in full:

  • Valid positions are a + 0 through a + N (where N is the element count). Computing anything outside that range is undefined behavior, even if you never dereference it.
  • Dereferenceable positions are only a + 0 through a + N - 1.
  • A single non-array object counts as an array of one element for these rules, so &x + 1 is a valid end pointer.

Breaking these rules is undefined behavior, not an error the compiler or runtime reports. Out-of-bounds reads often "work", reading whatever happens to be next in memory, which is exactly what makes them dangerous. Undefined Behavior and Memory Safety shows how -fsanitize=address catches them.

Pointer differences and comparisons

Subtracting two pointers into the same array gives the number of elements between them, as a signed integer of type std::ptrdiff_t. That's how you turn a found pointer back into an index.

C++ Finding an index with pointer subtraction

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Subtraction is defined only for two pointers into the same array (including its one-past-the-end position). The same goes for the relational operators <, <=, > and >=:

  • == and != work between any two pointers of compatible type. They tell you whether the pointers point to the same place.
  • <, >, <=, >= and - have meaningful results only for pointers into the same array (or members of the same object). Comparing pointers to two unrelated variables gives an unspecified result for <, and subtracting them is undefined behavior.
  • If you need a consistent ordering of arbitrary pointers (say, as keys in a std::map), use std::less<T*>, which the standard guarantees gives a strict total order even for unrelated pointers.

Pointers and multidimensional arrays

A 2D array is an array of arrays, stored row after row with no gaps. Decay turns it into a pointer to its first row, so arithmetic on that pointer steps whole rows. Many programs instead treat the storage as one flat run of elements, which is often simpler and faster:

C++ Rows, decay and flat access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The flat formula row * columns + column is the same index math you used in Multidimensional Arrays and Matrices with a flat std::vector. (Strictly speaking, walking from one row into the next through a pointer derived from &grid[0][0] is a gray area in the standard's wording, but every compiler supports it and a lot of real code depends on it. With a flat std::vector you avoid the question entirely.)

Modern code: keep the size with the pointer

Every bug in this lesson comes from the same root cause: a raw pointer knows where data is, but not how much of it there is. Modern C++ fixes that by bundling the two:

  • std::span<T> (C++20) is a pointer plus a length: a non-owning view over any contiguous elements. Pass std::span<const int> instead of (const int* data, std::size_t count).
  • std::array<T, N> and std::vector<T> own their elements and know their size; .at(i) checks bounds.
  • Iterators and ranges (v.begin(), std::ranges::find(v, x)) give you the same begin/end idea with container-aware types.
C++
#include <span>

int sum(std::span<const int> values) {   // accepts C arrays, std::array, std::vector
    int total = 0;
    for (int v : values) {
        total += v;
    }
    return total;
}

Pointer arithmetic is still worth understanding deeply, because you'll read it in libraries, C interfaces and performance-critical code, and because iterators behave the same way. But in new code, reach for a span or container first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int a[]{5, 10, 15, 20}; int* p = a + 1; What is p[2]?

    p points at a[1], and p[2] is *(p + 2), which is a[3] = 20.
  2. 2. On a system where int is 4 bytes, how many bytes apart are a and a + 3 for int a[10]?

    Pointer arithmetic counts elements, so a + 3 is 3 * sizeof(int) = 12 bytes after a.
  3. 3. For int a[3];, which of these is allowed?

    a + 3 is the one-past-the-end pointer. You may form and compare it, but not dereference it. a + 4 and a - 1 are undefined even to compute.
  4. 4. int x[]{1, 2, 3}; int* p = x; int y = *p++; What are y and *p afterwards?

    Postfix ++ binds tighter than *, so the expression reads *p (1) and then advances p to x[1], which holds 2.
  5. 5. Why does sizeof(values) give 8 inside void f(int values[]) on a 64-bit system?

    An array parameter is adjusted to a pointer, so the size information is gone. Use std::span or pass the size along.

Summary

  • An array name decays to a pointer to its first element in most expressions; sizeof, &arr and references are the main exceptions.
  • p + n moves n elements, not n bytes. a[i] is defined as *(a + i).
  • A begin pointer and a one-past-the-end pointer describe a half-open range [begin, end), the same model standard algorithms use.
  • You may compute pointers from a + 0 to a + N, but only dereference a + 0 to a + N - 1. Anything else is undefined behavior.
  • Subtracting pointers into the same array gives a std::ptrdiff_t element count; </> are only meaningful within one array. Use std::less to order unrelated pointers.
  • *p++ reads then advances; (*p)++ increments the element.
  • Prefer std::span, containers and iterators so the size travels with the data.

Next: const with Pointers and References, where you'll learn to read declarations like const int* const p and design const-correct functions.