C++ Reference ยท Types and Language Concepts
Pointers in C++
Reference for raw C++ pointers: declaring, dereferencing, nullptr, const placement, pointer arithmetic, dangling pointers and when to prefer references or smart pointers.
A pointer is an object that stores the address of another object (or of a function). You create one with T*, take an address with the unary &, and reach the pointed-to object with the unary * (dereference). Unlike a reference, a pointer can be reassigned, can be null, and can be copied around like any other value.
Raw pointers do not own anything: the language does not free what they point at, and it does not check that the target is still alive. That makes them the most common source of crashes and undefined behavior in C++. Modern code uses references for "refer to this" and smart pointers for ownership, and keeps raw pointers for optional, non-owning access and for low-level code.
int x = 10; int* p = &x; // p holds the address of x *p = 20; // x is now 20
Try it
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.
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.
Syntax
T* p; // pointer to T T* p = &obj; // initialize with an address T* p = nullptr; // null pointer *p // dereference: the object p points at p->member // same as (*p).member const T* p; // pointer to const T (T const* p is the same) T* const p = &obj; // const pointer to T const T* const p; // both void* p; // pointer to an unknown type T (*fp)(Args...); // pointer to function T C::* pm; // pointer to data member
| Operation | Description |
|---|---|
&obj |
Address of obj. The result type is T*. Overloaded operator& is bypassed by std::addressof. |
*p |
Dereference. Undefined behavior if p is null, dangling, or points past the end. |
p + n, p - n |
Moves by n elements (not bytes). Only valid inside one array, plus the one-past-the-end position. |
p - q |
Number of elements between two pointers into the same array, type std::ptrdiff_t. |
p == q, p < q |
Comparison. Ordering with < is only meaningful inside one array (use std::less for arbitrary pointers). |
static_cast<T*>(vp) |
Converts a void* back to its real type. |
Returns: & yields a prvalue pointer; * yields an lvalue of the pointed-to type.
Errors / undefined behavior: dereferencing a null or dangling pointer, forming a pointer more than one past the end of an array, subtracting pointers into different arrays, reading through a pointer of an unrelated type (strict aliasing), and using an uninitialized pointer.
Usage notes
- Always initialize. An uninitialized local pointer holds an indeterminate value; even copying it is undefined behavior. Write
int* p = nullptr;. - Use
nullptr, not0orNULL.nullptrhas its own type,std::nullptr_t, and picks the pointer overload instead of the integer one. See nullptr. - Reading
constdeclarations: read from the name outward.const int* pis "pointer to const int";int* const pis "const pointer to int".constapplies to the thing on its left, or to the right if nothing is on the left. - Dangling pointers. A pointer does not know when its target dies. Returning the address of a local variable, keeping a pointer into a
std::vectoracross apush_back, or using a pointer afterdeleteall leave it dangling. The pointer value is then unusable, even if it "still works" by accident. - Pointer arithmetic scales.
p + 1advancessizeof(T)bytes. Arithmetic onvoid*is not standard C++. - Arrays decay. In most expressions an array name becomes a pointer to its first element, and the size is lost. See Arrays.
- Ownership. Prefer
std::unique_ptrandstd::shared_ptrfor anything allocated withnew. A raw pointer in a modern interface means "borrowed, may be null". When it can never be null, use a reference. deleterules. Pairnewwithdelete,new[]withdelete[]. Deleting a null pointer is safe and does nothing. See new and delete.- Comparing and printing. Printing a pointer shows an address that changes from run to run, and a
char*is printed as a C string byoperator<<, not as an address. - Function pointers have a different syntax but follow the same rules: they can be null, copied and compared. For callable objects with state, see lambdas.