The Analogy: House Numbers on a Street of Identical Houses
A pointer holds an address. On a street where every house is the same size, "three doors down" is a perfectly good instruction — you do not need to know the distance in metres, because the house is the unit.
That is pointer arithmetic. p + 1 does not mean "one byte further along"; it means one element further along. If p is an int* on a typical machine, p + 1 is 4 bytes past p. If p is a double*, it is 8 bytes past. The compiler multiplies by sizeof(*p) for you, silently and always.
The analogy also warns you where it stops working. Counting doors only makes sense within one street: house 3 plus four doors is house 7, but house 7 plus four doors is somewhere in the next postcode, and the street directory says nothing about it. Pointer arithmetic is defined only inside a single array, plus the imaginary one-past-the-end address that marks where the street finishes. Step beyond that and you are not reading the wrong house — you are asking a question the language refuses to answer.
Syntax or Core Structure
#include <iostream>
int main() {
int values[5] = {10, 20, 30, 40, 50};
int* p = values; // arrays decay to a pointer to element 0
std::cout << *p << "\n"; // 10
std::cout << *(p + 1) << "\n"; // 20 -- one INT further, i.e. 4 bytes
std::cout << *(p + 3) << "\n"; // 40
std::cout << p[3] << "\n"; // 40 -- identical: p[i] IS *(p + i)
// Moving the pointer itself
++p; // now points at values[1]
std::cout << *p << "\n"; // 20
p += 2; // values[3]
std::cout << *p << "\n"; // 40
--p; // values[2]
std::cout << *p << "\n"; // 30
// Distance between two pointers, in ELEMENTS
int* first = values;
int* fourth = &values[3];
std::cout << "gap: " << (fourth - first) << "\n"; // 3, not 12
// Walking an array with pointers
for (int* it = values; it != values + 5; ++it) {
std::cout << *it << " ";
}
std::cout << "\n";
// The addresses themselves, to see the stride
for (int i = 0; i < 3; ++i) {
std::cout << "values + " << i << " -> "
<< static_cast<const void*>(values + i) << "\n";
}
}
The three consecutive addresses printed at the end differ by 4, not by 1. That is the entire mechanism: the type sets the step size.
Technical Depth: What Is Legal, and What the Stride Really Is
The scaling rule, stated precisely
For a pointer T* p, the expression p + n yields the address p + n * sizeof(T). You never write the multiplication.
char* c = ...; // c + 1 is 1 byte further
short* s = ...; // s + 1 is 2 bytes further
int* i = ...; // i + 1 is 4 bytes further (typically)
double* d = ...; // d + 1 is 8 bytes further
struct Big { double a, b, c; }; // 24 bytes
Big* b = ...; // b + 1 is 24 bytes further
This is why char* is sometimes used for byte-level work: it is the one pointer type whose arithmetic counts bytes, because sizeof(char) is 1 by definition.
The complete list of legal operations
| Operation | Result | Legal? |
|---|---|---|
p + n, p - n | Pointer | Yes, within one array (or one past the end) |
++p, --p, p += n | Pointer | Yes, same limits |
p - q | std::ptrdiff_t (element count) | Yes, if both point into the same array |
p == q, p != q, p < q | bool | Yes, same array |
*p | The element | Yes, if p is within bounds (not one-past-end) |
p + q | — | No. Adding two pointers is meaningless |
p * 2, p / 2 | — | No |
p + 1.5 | — | No. Integers only |
Note what is missing: you cannot add two pointers. "The address of house 3 plus the address of house 7" is not a place.
The one-past-the-end address
values + 5 for a five-element array is a valid address to hold and compare, but dereferencing it is undefined behaviour:
int values[5];
int* end = values + 5; // fine -- this is what end() means
// std::cout << *end; // UNDEFINED BEHAVIOUR
for (int* it = values; it != end; ++it) { /* correct */ }
That guarantee is exactly why the standard library's iterator ranges are half-open, [begin, end). values + 6 is not even valid to form, let alone dereference.
Out-of-bounds arithmetic is undefined, not "wrong"
int a[3] = {1, 2, 3};
int b[3] = {4, 5, 6};
std::cout << a[5]; // UB -- reads past a, not "b[2]"
std::cout << (b - a); // UB -- unrelated arrays
Two arrays declared next to each other are not guaranteed to be adjacent in memory, and even if they are, the standard does not let you traverse from one to the other. There is no bounds check anywhere in the language — a[5] will read something and print it without complaint, which is why these bugs survive so long.
Pointer subtraction and its type
int values[10];
int* first = &values[2];
int* last = &values[7];
std::ptrdiff_t gap = last - first; // 5, a SIGNED type
The result is std::ptrdiff_t from <cstddef>, which is signed because first - last should be -5. Do not store it in a std::size_t: an unsigned type turns -5 into an enormous positive number.
Traversal: three ways, one meaning
int v[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; ++i) std::cout << v[i]; // index
for (int* p = v; p != v + 5; ++p) std::cout << *p; // pointer
for (int x : v) std::cout << x; // range-based
All three compile to essentially the same machine code. The pointer form is not faster; it is simply what the other two are built from, and what <algorithm> operates on.
Pointers as iterators
This is the payoff for understanding the mechanism. A raw pointer satisfies everything the standard algorithms ask of an iterator, so they work directly on arrays:
#include <algorithm>
#include <numeric>
int v[6] = {5, 2, 9, 1, 7, 3};
std::sort(v, v + 6); // v decays to int*
int total = std::accumulate(v, v + 6, 0);
int* found = std::find(v, v + 6, 7);
if (found != v + 6) {
std::cout << "7 is at index " << (found - v) << "\n";
}
std::vector's iterators behave the same way for the same reason — v.end() - v.begin() is its size.
The precedence traps
int v[3] = {10, 20, 30};
int* p = v;
*p++; // dereference p, THEN advance p (postfix binds tighter than *)
(*p)++; // increment the ELEMENT p points at
*++p; // advance p, then dereference
++*p; // increment the element
*p++ and (*p)++ do entirely different things and differ by two characters. When it matters, use parentheses even where they are redundant — the reader should not have to recall the precedence table.
Arrays are not pointers
int v[5];
int* p = v;
std::cout << sizeof(v); // 20 -- the whole array
std::cout << sizeof(p); // 8 -- just the address
// v = p; // ERROR: an array name is not assignable
p = v; // fine
++p; // fine
// ++v; // ERROR
An array decays to a pointer to its first element in most expressions, which is why they feel interchangeable. They are not: the array knows its size, and the pointer does not. That lost size is why sizeof(data)/sizeof(data[0]) fails inside a function taking int data[].
const and pointers
const int* a; // pointer to const int: *a = 5 illegal, ++a fine
int* const b = v; // const pointer to int: *b = 5 fine, ++b illegal
const int* const c = v;// neither
Read them right to left. A function that walks an array it must not modify takes const int*, and can still advance its own local copy of the pointer freely.
What to use instead, in modern code
| Instead of | Prefer |
|---|---|
T* p plus a separate count | std::span<T> (C++20) |
p + i on a heap block | std::vector<T> and v[i] |
| Manual pointer loops | Range-based for, or <algorithm> |
p - q for a position | std::distance(q, p) |
Pointer arithmetic remains essential for reading C libraries, for genuinely low-level buffer code, and for understanding iterators. It is no longer the way to walk your own data.
Real World Example: A Packet Parser
Byte-level parsing is the place pointer arithmetic still earns its keep: you are handed a buffer and a length by some C API, and you have to walk it field by field. This example decodes a stream of simple telemetry packets, each laid out as a 1-byte type tag, a 2-byte little-endian length, and that many payload bytes.
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <optional>
#include <string>
#include <vector>
struct Packet {
std::uint8_t type = 0;
std::string payload;
};
// Reads one packet starting at *cursor. On success, advances *cursor past it.
std::optional<Packet> readPacket(const unsigned char** cursor,
const unsigned char* end) {
const unsigned char* p = *cursor;
if (end - p < 3) { // header needs 3 bytes
return std::nullopt;
}
Packet out;
out.type = *p; // byte 0: tag
++p;
std::uint16_t length = static_cast<std::uint16_t>(p[0]) |
static_cast<std::uint16_t>(p[1] << 8);
p += 2; // bytes 1-2: little-endian length
if (end - p < static_cast<std::ptrdiff_t>(length)) {
return std::nullopt; // truncated payload
}
out.payload.assign(reinterpret_cast<const char*>(p), length);
p += length;
*cursor = p; // commit only on success
return out;
}
std::vector<Packet> parseAll(const unsigned char* data, std::size_t size,
std::size_t& bytesConsumed) {
std::vector<Packet> packets;
const unsigned char* cursor = data;
const unsigned char* end = data + size; // one past the end -- never read
while (cursor != end) {
std::optional<Packet> next = readPacket(&cursor, end);
if (!next) break; // malformed tail: stop cleanly
packets.push_back(*next);
}
bytesConsumed = static_cast<std::size_t>(cursor - data); // ptr difference
return packets;
}
void hexDump(const unsigned char* data, std::size_t size) {
for (const unsigned char* p = data; p != data + size; ++p) {
std::cout << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<int>(*p) << " ";
}
std::cout << std::dec << std::setfill(' ') << "\n";
}
std::size_t countType(const unsigned char* data, std::size_t size,
std::uint8_t wanted) {
std::size_t used = 0;
std::vector<Packet> all = parseAll(data, size, used);
std::size_t n = 0;
for (const Packet& pkt : all) {
if (pkt.type == wanted) ++n;
}
return n;
}
int main() {
const unsigned char stream[] = {
0x01, 0x05, 0x00, 'h', 'e', 'l', 'l', 'o',
0x02, 0x03, 0x00, 'a', 'b', 'c',
0x01, 0x04, 0x00, 'd', 'o', 'n', 'e',
0x02, 0x09, 0x00, 'c', 'u', 't' // truncated on purpose
};
const std::size_t streamSize = sizeof(stream) / sizeof(stream[0]);
std::cout << "raw (" << streamSize << " bytes):\n";
hexDump(stream, streamSize);
std::size_t consumed = 0;
std::vector<Packet> packets = parseAll(stream, streamSize, consumed);
std::cout << "\nparsed " << packets.size() << " packets, "
<< consumed << " of " << streamSize << " bytes consumed\n";
for (const Packet& pkt : packets) {
std::cout << " type " << static_cast<int>(pkt.type)
<< ", " << pkt.payload.size() << " bytes: "
<< pkt.payload << "\n";
}
std::cout << "\ntrailing bytes ignored: "
<< (streamSize - consumed) << "\n";
std::cout << "type 1 packets: " << countType(stream, streamSize, 1) << "\n";
}
Output:
raw (27 bytes):
01 05 00 68 65 6c 6c 6f 02 03 00 61 62 63 01 04 00 64 6f 6e 65 02 09 00 63 75 74
parsed 3 packets, 21 of 27 bytes consumed
type 1, 5 bytes: hello
type 2, 3 bytes: abc
type 1, 4 bytes: done
trailing bytes ignored: 6
type 1 packets: 2
Every pointer operation here is doing something the index version could not do as cleanly. end = data + size is the one-past-the-end address, formed and compared but never dereferenced — the loop condition is cursor != end, the half-open range the standard explicitly permits. end - p is pointer subtraction used as a bounds check before every read: "are there at least three bytes left?" is a question about the remaining distance, and subtracting the pointers answers it directly. That check is the difference between a parser and a buffer overrun; without it, a malformed length field would send p += length sailing past the end of the array, and the language would not object.
readPacket takes const unsigned char** cursor — a pointer to the caller's pointer — because it must advance the caller's position, and it assigns *cursor = p only at the very end. That ordering is deliberate: on a truncated packet the function returns std::nullopt having touched nothing, so the caller's cursor still marks the last known-good position. That is why consumed comes out as 21 rather than 27, and why the caller can report exactly how much of the stream was usable.
The type choices carry real weight. The buffer is unsigned char because plain char may be signed, and p[1] << 8 on a signed byte with the high bit set would sign-extend and corrupt the length. The comparison end - p < static_cast<std::ptrdiff_t>(length) casts deliberately: pointer subtraction yields the signed std::ptrdiff_t, and comparing it against an unsigned std::uint16_t without the cast would convert the left side to unsigned, turning any negative remainder into a huge positive value and defeating the check. reinterpret_cast<const char*>(p) appears exactly once, at the boundary where raw bytes become a std::string, and the two-argument assign is used rather than a constructor from p alone because the payload is not null-terminated — its length comes from the header, not from scanning for a zero.
Note also hexDump, which takes const unsigned char*: it walks with its own local pointer, incrementing freely, while const guarantees it cannot alter the caller's buffer. That is const int* rather than int* const, and it is the correct signature for any read-only traversal.
In new code you would express the buffer as std::span<const unsigned char>, which carries the length with the pointer and makes the "three bytes left?" check harder to forget. The arithmetic underneath would be identical — span is a pointer and a size, made honest.
Common Mistakes
- Thinking
p + 1means one byte. It means one element. Fordouble*that is 8 bytes. - Going out of bounds.
a[5]on a three-element array is undefined behaviour, and there is no check to catch it. - Dereferencing the one-past-the-end pointer.
*(v + n)is UB even thoughv + nis a legal address to hold. - Comparing or subtracting pointers into different arrays. Undefined, even if they happen to sit next to each other.
- Storing a pointer difference in
std::size_t. The result is signed; a negative gap becomes a vast positive number. - Confusing
*p++with(*p)++. One advances the pointer, the other changes the value. - Expecting
sizeofto work through a pointer.sizeof(p)is the address size, not the array's. - Assuming
sizeof(int)is 4 everywhere. Usesizeofrather than a hardcoded stride. - Arithmetic on a
void*. The step size is unknown, so it is not allowed. Cast tochar*for byte work. - Doing pointer arithmetic on a container that may reallocate. A
push_backinvalidates every pointer into a vector.
Best Practices
- Prefer
std::span, containers and range-basedforfor your own data. Keep pointer arithmetic at C boundaries. - Use the half-open range
[begin, end). It is what the library does and it makes the loop condition!=, not<. - Bounds-check with pointer subtraction before every read when parsing untrusted bytes.
- Pass a pointer and a length together, always. A bare pointer has lost the one fact you need.
- Use
const T*for read-only traversal. - Use
unsigned charfor raw bytes, never plainchar, to avoid sign extension. - Parenthesise mixed
*and++even when precedence would have got it right. - Use
std::ptrdiff_tfor differences andstd::size_tfor sizes, and cast explicitly when comparing them. - Reach for
<algorithm>. Pointers are iterators, sostd::sort(v, v + n)already works.
Practice Exercises
- Declare
double temps[6]and print each element three ways:temps[i],*(temps + i), and a pointer-walking loop. Then printtemps + 0,temps + 1andtemps + 2as addresses and state the stride in bytes. - Write
int sumRange(const int* begin, const int* end)that adds every element in a half-open range, and call it on a whole array and on a slice of the middle. Explain why it never dereferencesend. - Write
const unsigned char* findByte(const unsigned char* data, std::size_t size, unsigned char target)returning a pointer to the first match ornullptr. Convert the result to an index with pointer subtraction. - Write a function that reverses an array in place using two pointers moving toward each other, stopping when they meet. Explain why the loop condition must be
left < rightand notleft != right.