# Pointers, arrays and pointer arithmetic

> A pointer value is not just an address; it points to an object, past the end of one, nowhere, or it is invalid. This page covers array-to-pointer decay and where it stops, what arithmetic and comparison the standard defines, multidimensional arrays, function pointers, nullptr, references and std::to_address.

- **Source:** C++ Atlas (https://cppatlas.com/topics/pointers-arrays-and-pointer-arithmetic)
- **Track:** Memory model
- **Estimated reading time:** 14 minutes
- **ISO C++ clauses:** [basic.compound] (https://eel.is/c++draft/basic.compound), [basic.stc.general] (https://eel.is/c++draft/basic.stc.general), [conv.array] (https://eel.is/c++draft/conv.array), [dcl.fct] (https://eel.is/c++draft/dcl.fct), [expr.add] (https://eel.is/c++draft/expr.add), [expr.rel] (https://eel.is/c++draft/expr.rel), [expr.eq] (https://eel.is/c++draft/expr.eq), [comparisons.general] (https://eel.is/c++draft/comparisons.general), [basic.fundamental] (https://eel.is/c++draft/basic.fundamental), [dcl.ref] (https://eel.is/c++draft/dcl.ref), [pointer.conversion] (https://eel.is/c++draft/pointer.conversion)
- **cppreference links:** [Pointer declaration](https://en.cppreference.com/w/cpp/language/pointer), [Array declaration](https://en.cppreference.com/w/cpp/language/array), [Additive operators](https://en.cppreference.com/w/cpp/language/operator_arithmetic), [Comparison operators](https://en.cppreference.com/w/cpp/language/operator_comparison), [std::less](https://en.cppreference.com/w/cpp/utility/functional/less), [std::nullptr_t](https://en.cppreference.com/w/cpp/types/nullptr_t), [std::to_address](https://en.cppreference.com/w/cpp/memory/to_address)
- **Prerequisites:** object-lifetime-and-storage, strict-aliasing-and-undefined-behavior

## The one idea

The hardware sees an address. The abstract machine sees a pointer value, and [basic.compound] says every value of an object pointer type is exactly one of four things: a pointer to an object, a pointer past the end of an object, the null pointer value, or an invalid pointer value. Arithmetic, comparison and dereference are all defined in terms of which of the four you hold and which object it relates to, never in terms of the bits.

> **Mental model.** A pointer is an address plus a claim about which object it belongs to. The address says where; the claim says what you may do. Two pointers can hold the same address and still have different values, because one points to an object and the other points past the end of its neighbour.

The topic on strict aliasing introduces this idea, which is often called provenance, and the type-access rules that go with it. This page works through the rest of the pointer model.

## Four kinds of pointer value

A pointer past the end of an object represents the first byte after it. You may form it, copy it, compare it and subtract it, but you may not dereference it. Every object counts as an array of one element for this purpose, so `&x + 1` is a valid past-the-end pointer even for a scalar.

A pointer becomes invalid when the storage it points into reaches the end of its duration: after `delete`, after the block holding an automatic variable exits, after `free`. Dereferencing an invalid pointer, or passing it to a deallocation function, is undefined. Every other use, including copying it, comparing it, or printing it, is implementation-defined, because some architectures trap when an invalid address is merely loaded into a register.

```cpp
int* dangling() {
  int* p = new int(1);
  delete p;          // p now holds an invalid pointer value
  int* q = p;        // implementation-defined, not undefined
  return q;          // *q, or delete q, would be undefined
}
```

Equality between a past-the-end pointer and a pointer to some unrelated object is a trap of its own. If `a` and `b` happen to be adjacent, `a + 1` and `&b` may have the same address. [expr.eq] makes the result of `a + 1 == &b` unspecified in that case, which lets an optimizer fold it to `false` in one place and compute `true` in another; GCC has been observed doing exactly that.

## Array-to-pointer decay and where it stops

An lvalue or rvalue of type "array of N `T`" converts to a prvalue `T*` pointing to the first element. This conversion happens in almost every expression, which is why arrays look like pointers. It does not happen in these places:

- the operand of `sizeof`, `decltype`, `typeid` and unary `&`;
- binding a reference to the array, including deducing `T` for a `const T&` parameter;
- initializing a `char` array from a string literal;
- the range of a range-based `for`, and a structured binding declaration;
- a lambda capture by copy, which copies the whole array.

The most surprising rule runs the other way. A function parameter declared as an array is adjusted to a pointer, so `void f(int a[10])` declares `void f(int* a)`, and the `10` is ignored.

```cpp
#include <type_traits>

int a[4];
static_assert(std::is_same_v<decltype(a), int[4]>);       // no decay in decltype
static_assert(std::is_same_v<decltype(&a), int(*)[4]>);   // pointer to the whole array
static_assert(std::is_same_v<decltype(+a), int*>);        // unary + forces decay

void f(int p[10]) {
  static_assert(std::is_same_v<decltype(p), int*>);       // the parameter is a pointer
}

template <class T> constexpr bool by_value(T)      { return std::is_array_v<T>; }
template <class T> constexpr bool by_ref(const T&) { return std::is_array_v<T>; }
static_assert(!by_value(a) && by_ref(a));                 // T is int* vs int[4]
```

`&a` and `a` usually hold the same address but have different types, so `&a + 1` steps over the whole array while `a + 1` steps over one `int`.

## Arithmetic stays inside one array

[expr.add] defines `P + J` only when `P` points to element `i` of an array of `n` elements and `0 <= i + J <= n`. Anything else is undefined, whether or not the result is dereferenced. Subtraction `P - Q` is defined only when both point into, or one past the end of, the same array, and gives `i - j` as a `std::ptrdiff_t`.

`std::ptrdiff_t` is a signed type, and `std::size_t` can describe larger objects than it can measure. If an array of `char` is longer than `PTRDIFF_MAX` bytes, subtracting pointers at its two ends gives a difference that is not representable, and the behavior is undefined. On 64-bit systems no allocation is that large in practice. On 32-bit systems a buffer of more than 2 GB is conceivable, which is one reason GCC refuses to declare an object larger than `PTRDIFF_MAX` and glibc's `malloc` refuses such requests.

### Multidimensional arrays

`int m[3][4]` is an array of three arrays of four `int`. It decays to `int (*)[4]`, and `m[i]` is itself an array that decays to `int*`. The twelve `int` objects are contiguous, but they are not one array of twelve. A pointer obtained from `m[0]` belongs to a four-element array, so `&m[0][0] + 4` is its past-the-end pointer, and `(&m[0][0])[5]` is out of bounds even though `m[1][1]` lives at that address.

```cpp
constexpr int flat() {
  int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
  int* p = &m[0][0];
  return p[3];   // undefined: p points into m[0], which has three elements
}
// constexpr int v = flat();   // rejected by GCC 16 and Clang 21 as not a constant expression
```

Code that walks a matrix with a single `int*` is common and works on every mainstream compiler, but the standard does not bless it. `std::mdspan` in C++23, covered in the topic on span and mdspan, is the sanctioned way to view one flat buffer as several dimensions.

> **Pitfall.** Treating an object as bytes and stepping through it with `unsigned char*` is universally relied on, for example in `memcpy` implementations and hashing, but the C++23 wording does not clearly define pointer arithmetic over an object's representation. The proposal P1839 addresses that gap. Prefer `std::memcpy`, `std::bit_cast` or `std::as_bytes` where you can.

## Comparing pointers

Equality with `==` and `!=` works for any two pointers of compatible type, with the past-the-end caveat already described. Relational comparison with `<` and friends is specified only within one object: later array elements compare greater, and later-declared non-static data members compare greater provided neither is a zero-size subobject. Before C++23 that member rule also required the members to have the same access; P1847 dropped the condition. For pointers to unrelated objects the result is unspecified, not undefined, which differs from C, where such a comparison is undefined.

```cpp
struct P { int a; int b; };

constexpr bool members_ordered() {
  P p{};
  return &p.a < &p.b;            // guaranteed true: b is declared later
}
static_assert(members_ordered());

bool unrelated(int& x, int& y) {
  return &x < &y;                // unspecified result, and never a constant expression
}
```

`std::less<T*>`, `std::ranges::less` and the other comparison function objects are guaranteed to yield an implementation-defined strict total order over pointers, consistent with the built-in operators wherever those are specified. That is why `std::set<T*>` and `std::map<T*, V>` work. The guarantee does not make the result usable in constant evaluation for unrelated pointers; both GCC 16 and Clang 21 reject that.

> **Standardese.** [expr.rel] says that when two pointers do not point into the same array or into the same object, neither is required to compare greater than the other, and [comparisons.general] separately requires `std::less` and its relatives to produce an implementation-defined strict total order consistent with the built-in operators.

## Pointer-interconvertibility, function pointers and nullptr

Two objects are pointer-interconvertible when a `reinterpret_cast` between pointers to them yields a pointer to the other object: a standard-layout class object and its first non-static data member, a union and its members, and an object and itself. The strict-aliasing topic explains why other casts only relabel the pointer. C++20 added `std::is_pointer_interconvertible_with_class(&S::m)` to test the member case; GCC 16 supports it and libc++ in LLVM 21 does not yet.

A function name decays to a pointer to function, and a function pointer cannot take part in arithmetic. Function pointers may be converted to other function pointer types with `reinterpret_cast`, and converting back yields the original, but calling through the wrong type is undefined. Converting a function pointer to `void*` is conditionally-supported; POSIX requires it, which is how `dlsym` works.

`nullptr` is a prvalue of type `std::nullptr_t`, which is neither a pointer type nor an integer type. It converts to every pointer and pointer-to-member type, but not to `int`. It converts to `bool` only in direct-initialization, as in `bool b(nullptr);`, and `bool b = nullptr;` is ill-formed. `NULL` is an implementation-defined null pointer constant, often `0` or `0L`, so `g(NULL)` may pick the integer overload or be ambiguous; `nullptr` always selects the pointer overload.

```cpp
#include <cstddef>

void g(int);
void g(char*);

void call() {
  g(nullptr);    // g(char*)
  g(0);          // g(int)
}

static_assert(sizeof(std::nullptr_t) == sizeof(void*));   // guaranteed by [basic.fundamental]
```

## References, and std::to_address

A reference is an alias, not an object. It has no address of its own, `sizeof` on a reference type yields the size of the referenced type, and [dcl.ref] leaves it unspecified whether a reference requires storage at all. Implementations represent a reference member or parameter as a pointer when they need storage, and a local reference to a known object usually needs none. A reference cannot be null in a valid program: forming one from a null pointer is already undefined. It also cannot be reseated, which is why a reference member makes a class's implicit copy assignment operator deleted.

C++20's `std::to_address(p)` returns a raw pointer equal to what `p` points to, without dereferencing. For a raw pointer it returns `p`. For a fancy pointer or a contiguous iterator it uses `std::pointer_traits<P>::to_address` if provided, and otherwise calls `p.operator->()` and recurses. The practical use is getting a raw pointer from an end iterator, where `&*it` would dereference a past-the-end iterator.

```cpp
#include <memory>
#include <vector>

int* end_pointer(std::vector<int>& v) {
  return std::to_address(v.end());   // OK; &*v.end() would be undefined
}
```

## What to remember

- A pointer value points to an object, points past the end of one, is null, or is invalid. Equal addresses do not imply equal values.
- Dereferencing or deleting an invalid pointer is undefined; any other use of it, even copying, is implementation-defined.
- `p + 1 == &other` with `p` past the end is unspecified.
- Arrays decay almost everywhere, except under `sizeof`, `decltype`, unary `&`, reference binding and a few initializations. Array parameters are really pointers.
- Arithmetic is defined only within one array plus one past the end; `ptrdiff_t` overflow in subtraction is undefined.
- `int m[3][4]` is three arrays of four, not one of twelve; indexing past a row is undefined. Use `std::mdspan`.
- `<` on unrelated pointers is unspecified in C++ (undefined in C); `std::less` gives a total order.
- Function pointers do no arithmetic, and calling through a mismatched type is undefined.
- `nullptr` converts to pointers but not integers, and to `bool` only by direct-initialization; `sizeof(std::nullptr_t) == sizeof(void*)`.
- References are not objects and may not occupy storage; `std::to_address` (C++20) gets a raw pointer without dereferencing.

## Concept Map Outline

- **Pointers and arrays:** A pointer value is an address plus a claim about which object it belongs to.
  - **Pointer values:** Every object pointer value is one of exactly four kinds.
    - **Past-the-end:** May be formed, copied, compared and subtracted, never dereferenced.
    - **Invalid:** After storage ends; dereference or delete is UB, any other use is implementation-defined.
    - **Same address, different value:** p + 1 == &neighbour is unspecified.
  - **Decay:** Arrays convert to a pointer to their first element in most expressions.
    - **No decay:** Under sizeof, decltype, typeid, unary &, reference binding and range-for.
    - **Array parameters:** void f(int a[10]) declares f(int*); the bound is ignored.
    - **Deduction:** By-value T deduces int*; const T& deduces int[N].
    - **&a vs a:** &a is int(*)[N]; &a + 1 steps over the whole array.
  - **Arithmetic:** Defined only within one array, counting one past the end.
    - **Out of range:** Forming a pointer outside [0, n] is UB even without a dereference.
    - **ptrdiff_t overflow:** Subtracting across a char array longer than PTRDIFF_MAX is UB.
    - **Multidimensional:** int m[3][4] is three arrays of four; indexing past a row is UB.
    - **Byte walking:** Stepping through object bytes is relied on but under-specified; P1839 addresses it.
  - **Comparison:** == works everywhere; < is only specified within one object.
    - **Unrelated with <:** Unspecified in C++, undefined in C, never a constant expression.
    - **Member order:** Later-declared members compare greater; C++23 dropped the same-access condition.
    - **std::less:** Guarantees an implementation-defined strict total order over pointers.
  - **Other pointer kinds:** Function pointers, nullptr_t and interconvertible objects follow their own rules.
    - **Interconvertible:** Standard-layout object and first member, or union and member; other casts only relabel the pointer.
    - **Function pointers:** No arithmetic; calling through a mismatched type is UB; to void* is conditional.
    - **std::nullptr_t:** Converts to pointers, not integers; to bool only by direct-initialization.
  - **References and to_address:** Aliases without object identity, and raw pointers without dereferencing.
    - **References:** Not objects; may need no storage; never null or reseated in valid code.
    - **std::to_address:** C++20: raw pointer from a fancy pointer or iterator, safe for end().

## Standardese Quiz Questions

### Question 1 [warmup] ([conv.array], [expr.unary.op])

What is the type of `p`?

```cpp
int a[4] = {};
auto p = &a;
```

A. `int*`
B. `int**`
C. `int (*)[4]`
D. `int (&)[4]`

**Answer (C):** `int (*)[4]`

**Why:** Array-to-pointer conversion is not applied to the operand of unary `&`, so `&a` takes the address of the whole array and has type pointer to array of four `int`. It usually holds the same address as `a` after decay, which is why `int*` is tempting, but `p + 1` steps over all four elements. `int**` would need an object of type `int*` to point to, and there is none.

### Question 2 [warmup] ([conv.ptr], [basic.fundamental], [over.ics.rank])

What does this program print?

```cpp
#include <cstdio>

void f(int) { std::puts("int"); }
void f(char*) { std::puts("char*"); }

int main() {
  f(nullptr);
  f(0);
}
```

A. `char*` then `int`
B. `int` then `int`
C. Ill-formed: `f(nullptr)` is ambiguous
D. `int` then `char*`

**Answer (A):** `char*` then `int`

**Why:** `nullptr` has type `std::nullptr_t`, which converts to any pointer type but not to `int`, so only `f(char*)` is viable. The literal `0` is an exact match for `f(int)`, while converting it to `char*` would be a null pointer conversion, which ranks lower. That asymmetry is why `nullptr` replaced `0` and `NULL` for null pointers.

### Question 3 [warmup] ([dcl.fct], [expr.sizeof])

What does this program print?

```cpp
#include <cstdio>

void f(int a[10]) {
  std::printf("%d\n", sizeof(a) == sizeof(int*));
}

int main() {
  int x[10] = {};
  f(x);
}
```

A. `0`, because `a` has type `int[10]`
B. `1`
C. Ill-formed: `sizeof` cannot be applied to an array parameter
D. It depends on the platform

**Answer (B):** `1`

**Why:** A parameter declared with an array type is adjusted to the corresponding pointer type, so `a` has type `int*` and the bound `10` is ignored. `sizeof(a)` is therefore exactly `sizeof(int*)` on every implementation, and compilers warn about it with `-Wsizeof-array-argument`. To keep the bound, take the array by reference, `int (&a)[10]`, or use `std::span`.

### Question 4 [tricky] ([expr.add], [dcl.array])

What does the standard say about `p[3]`?

```cpp
int read() {
  int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
  int* p = &m[0][0];
  return p[3];
}
```

A. It reads `m[1][0]` and returns 4, because rows are contiguous
B. Implementation-defined
C. Unspecified: it returns 4 or an indeterminate value
D. Undefined behavior

**Answer (D):** Undefined behavior

**Why:** `p` points to the first element of `m[0]`, which is an array of three `int`. [expr.add] defines `p + 3` as the past-the-end pointer of that array, and dereferencing a past-the-end pointer is undefined, even though `m[1][0]` occupies that address. The contiguity in the first option is real, which is why the code usually appears to work, but contiguity does not make two arrays into one. Both GCC 16 and Clang 21 reject this function in a constant expression.

### Question 5 [tricky] ([temp.deduct.call], [conv.array])

What does this program print?

```cpp
#include <cstdio>
#include <type_traits>

template <class T> bool by_value(T) { return std::is_array_v<T>; }
template <class T> bool by_ref(const T&) { return std::is_array_v<T>; }

int main() {
  int a[3] = {1, 2, 3};
  std::printf("%d%d\n", by_value(a), by_ref(a));
}
```

A. `11`
B. `00`
C. `01`
D. `10`

**Answer (C):** `01`

**Why:** When the parameter is not a reference, template argument deduction applies the array-to-pointer conversion to the argument type, so `T` is `int*`. When the parameter is a reference, no decay happens and `T` is deduced as `int[3]`, binding `const int (&)[3]`. That is how `std::size` and `std::begin` recover an array's bound.

### Question 6 [tricky] ([expr.rel], [comparisons.general])

In C++23, what does the standard say about the value `cmp()` returns?

```cpp
bool cmp() {
  int a = 0, b = 0;
  return &a < &b;
}
```

A. Undefined behavior, as in C
B. It is `true`, because `a` is declared first
C. Unspecified
D. Implementation-defined, and documented by the compiler

**Answer (C):** Unspecified

**Why:** `a` and `b` are separate complete objects, not elements of one array or members of one object, so [expr.rel] requires neither pointer to compare greater than the other. The result is unspecified: the program is valid, but it may be `true` or `false`, and the implementation need not document which. In C the same comparison is undefined, which is the tempting first answer. Declaration order only orders members of the same class object; for an order over arbitrary pointers use `std::less<int*>`.

### Question 7 [standardese] ([basic.stc.general], [basic.compound])

In C++23, what does the standard say about the line that initializes `q`?

```cpp
int main() {
  int* p = new int(1);
  delete p;
  int* q = p;
  (void)q;
}
```

A. Well-defined: only dereferencing a dangling pointer is restricted
B. Implementation-defined behavior
C. Undefined behavior
D. Unspecified behavior

**Answer (B):** Implementation-defined behavior

**Why:** After `delete p`, the value of `p` is an invalid pointer value, because the storage it pointed to has reached the end of its duration. [basic.stc.general] makes indirection through an invalid pointer and passing it to a deallocation function undefined, and every other use, including copying it, implementation-defined. The rule exists because some architectures can trap when an invalid address is loaded. Copying was undefined until CWG 1438, so older material gives the third answer.

### Question 8 [standardese] ([basic.fundamental], [basic.compound], [expr.sizeof])

Which of these does the C++23 standard guarantee on every conforming implementation?

A. `sizeof(int*) == sizeof(char*)`
B. `sizeof(void (*)()) == sizeof(void*)`
C. `sizeof(int&) == sizeof(int*)`
D. `sizeof(std::nullptr_t) == sizeof(void*)`

**Answer (D):** `sizeof(std::nullptr_t) == sizeof(void*)`

**Why:** [basic.fundamental] states that `sizeof(std::nullptr_t)` equals `sizeof(void*)`. Only `char*` and `void*` are guaranteed to share a representation, so `int*` may differ on word-addressed machines. Function pointers can be larger than object pointers, and converting between them is only conditionally-supported. `sizeof` applied to a reference type yields the size of the referenced type, so `sizeof(int&)` is `sizeof(int)`.
