Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 171 ยท Pointers, References and Memory

Pointers

Learn C++ pointers from scratch - addresses, the & and * operators, nullptr, pointers to structs with ->, pointers to pointers, and why null dereference is UB.

Every object in a running program lives somewhere in memory, and every location in memory has an address: a number that says where it is. A pointer is a variable whose value is such an address. Instead of holding an int, a pointer holds "the place where an int lives", and through it you can read or change that int.

Pointers are what make C++ able to talk to hardware, build linked data structures, share one object between many parts of a program and work with memory the operating system hands out. They're also the source of many famous bugs, because a pointer can point at nothing, at something that no longer exists, or at the wrong place entirely. This lesson teaches the core mechanics carefully: taking addresses with &, following them with *, nullptr, the -> operator, pointers to pointers, and the rules that keep you out of undefined behavior. If you just read References, you'll see how pointers are the more flexible (and more dangerous) cousin.

Addresses and the & operator

Put & in front of a variable to get its address. The result is a pointer. Its type is the variable's type followed by *: the address of an int is an int*, the address of a double is a double*.

C++ Taking addresses

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 addresses are printed in hexadecimal and change from run to run, because modern operating systems place the stack at a random location each time (address space layout randomization, a security feature). On a 64-bit system every object pointer is 8 bytes, whatever it points to.

std::format and std::println print only void*, const void* and nullptr as addresses, so you convert with static_cast<void*>(p) (or const void* for pointers to const). Printing int* directly doesn't compile, which prevents accidentally printing an address when you meant the value. With std::cout << p any object pointer prints as an address, except char*, which cout treats as a C string.

Dereferencing with *

The * operator in an expression dereferences a pointer: it gives you the object at that address. *p isn't a copy; it's the object itself, so you can read it and assign to it.

C++ Reading and writing through a pointer

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.

Here's where pointers differ from references: p = &other; changes which object p points to. With a reference, assignment always went to the original object. With a pointer, you choose: p = ... changes the pointer, *p = ... changes the pointee.

The * symbol does two jobs, which confuses everyone at first:

  • In a declaration, int* p means "p is a pointer to int".
  • In an expression, *p means "the object p points to".

The same is true of &: in a declaration (int& r) it makes a reference, in an expression (&x) it takes an address.

Where to put the star

int* p, int *p and int * p all mean the same thing. Modern C++ style usually writes int* p, attaching the star to the type. But the star actually belongs to each declarator, which bites when you declare several variables:

C++
int* a, b;     // a is int*, b is a plain int!
int *c, *d;    // both pointers, but easy to get wrong
int* e = nullptr;
int* f = nullptr;   // best: one declaration per line

nullptr: pointing at nothing

A pointer that doesn't point at any object should hold the null pointer value, written nullptr (C++11). You can test a pointer against it, and a pointer converts to bool: null is false, anything else is true.

C++ nullptr and checking before use

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.

Returning a pointer that may be null is a traditional way to say "here's the object, or nothing". Modern alternatives include returning an iterator (and comparing with end()) or std::optional, but you'll see nullable pointers everywhere in real code.

Dereferencing a null pointer is undefined behavior. On desktop systems it usually crashes with a segmentation fault (SIGSEGV), but the standard promises nothing: the optimizer is allowed to assume a dereferenced pointer was never null and remove your later checks. Always check a pointer that might be null before using * or ->.

Old code uses NULL or 0 for null pointers. Both are integers in disguise, which causes surprises with overloaded functions (f(NULL) may call f(int) instead of f(int*)). Always write nullptr.

Uninitialized and dangling pointers

Null pointers are the safe kind of bad pointer, because you can test for them. Two other kinds can't be detected by looking at the pointer:

  • An uninitialized pointer (int* p; inside a function) holds a garbage address. Using it is undefined behavior. Initialize every pointer, to nullptr if you have nothing better.
  • A dangling pointer holds the address of an object that has been destroyed: a local variable of a function that has returned, a vector element after reallocation, or heap memory after delete. It looks like a perfectly normal address.
C++
int* make_dangling() {
    int local = 5;
    return &local;   // warning: address of local variable 'local' returned
}                    // local dies here; the caller gets a dangling pointer

Undefined Behavior and Memory Safety shows how sanitizers catch these at run time.

Pointers to structs and the -> operator

When a pointer points to a struct or class, you reach its members through it. (*p).member works but is clumsy (the parentheses are required because . binds tighter than *), so C++ offers the arrow: p->member means exactly (*p).member.

C++ The arrow operator with a struct pointer

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.

1000 + 250 = 1250, and 4 % interest gives 1300.00. The nullptr call shows why some APIs take a pointer instead of a reference: "no account" is a meaningful input they handle.

Pointers to pointers

A pointer is itself an object with an address, so you can point at it. An int** is a pointer to an int*. Dereference once to get the inner pointer, twice to get the int.

C++ A pointer to a pointer

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.

You'll meet T** in two places: C APIs that need to change a caller's pointer (like reset_to_null above, or allocation functions that "return" a pointer through a parameter), and char** argv in int main(int argc, char** argv), which is an array of C strings. In your own C++ code, a reference to a pointer (int*& p) does the same job as int** with less noise, and returning a value is usually better still.

Pointer types matter

A pointer's type says how to interpret the bytes at its address, so C++ won't silently convert between unrelated pointer types:

C++
int number = 65;
int* ip = &number;
double* dp = ip;                         // error: cannot convert int* to double*
void* anything = ip;                     // fine: any object pointer converts to void*
int* back = static_cast<int*>(anything); // converting back needs a cast

void* means "an address of something, type unknown". You can store and pass it, but not dereference it: you must cast it back to the right type first. It's common in C interfaces (malloc, memcpy, thread APIs) and rare in modern C++, where templates keep the type information. Reading an object through a pointer of the wrong type (via reinterpret_cast) is usually undefined behavior; Type Conversions and Casts explains the exceptions.

The kinds of pointers, in one place

People talk about "wild", "dangling", "null" and "void" pointers as if they were different types. They are really different states or roles of the same thing, and the names are worth knowing:

Name What it is Is it safe to use?
Wild (uninitialized) Declared but never assigned, like int* p; inside a function. Holds garbage. No: even reading the pointer value is undefined behavior
Null Holds nullptr: it points at no object Safe to compare and copy, never to dereference
Dangling Once pointed at an object that has since been destroyed or moved (freed heap memory, a returned local, an invalidated vector element) No: it looks valid but isn't
Void (void*) Points at an object of unknown type Safe to store and pass; cast back before use
Valid Points at a live object of the matching type Yes

Two rules prevent almost all trouble: initialize every pointer (to an address or to nullptr), and set a raw owning pointer to nullptr after delete. Better still, don't own memory through raw pointers at all.

A bit of history explains old code you may meet: C++98 had std::auto_ptr, a smart pointer that copied by moving, so b = a; silently left a null. That surprised everyone, and it was deprecated in C++11 and removed in C++17. Its job is done by std::unique_ptr, where the move is explicit.

Pointers to members

An ordinary pointer holds the address of an object. A pointer to member holds a position inside a class: "the score field", or "the add function", without naming any object yet. You apply it to an object later, with .* (object on the left) or ->* (pointer on the left):

C++ Data and function member 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.

The program prints Ada: 32 (10 set to 20, plus 5, plus 7). The syntax T C::* reads "pointer to a member of C of type T". Notice that &Player::score is not the address of any score; it only says which member. A member function pointer is not a plain function pointer either (a member function needs an object to run on), which is why std::function, lambdas and std::invoke are usually easier. Member pointers still appear inside libraries: std::invoke(&Player::add, ada, 3), std::mem_fn, and projections in ranges, such as std::ranges::sort(players, {}, &Player::score).

Pointers vs references, in practice

C++ The same function three ways

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 output is a = 2, b = 6, c = 6. Guidelines that experienced C++ programmers follow:

  • Prefer references for parameters that must refer to an object.
  • Use a pointer (T*) when null is a valid "not provided" value, or when the pointer must later point elsewhere.
  • A raw T* should mean "I'm looking at this, I don't own it". Objects you create on the heap belong in containers or smart pointers (std::unique_ptr), not in raw pointers you have to remember to free.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. int x = 5; int* p = &x; *p = *p * 2; What is x?

    *p is x itself, so the statement reads x, doubles it and stores 10 back into x.
  2. 2. int* a, b; What are the types of a and b?

    The star belongs to each declarator, not to the type, so only a is a pointer. Declare one pointer per line to avoid this.
  3. 3. int x = 1, y = 2; int* p = &x; p = &y; *p = 9; What are x and y?

    Unlike a reference, a pointer can be reassigned. p = &y makes p point to y, so *p = 9 changes y.
  4. 4. What does the C++ standard say happens when you dereference a null pointer?

    Null dereference is undefined behavior. It often crashes with a segmentation fault, but nothing is guaranteed, and the optimizer may assume it never happens.
  5. 5. Given Account* p, which expression means the same as p->balance?

    The arrow is shorthand for dereference-then-member. *p.balance would parse as *(p.balance), which doesn't compile.

Summary

  • A pointer holds an address. &x gives the address of x; the type of &x for an int x is int*.
  • *p is the object p points to: you can read it and assign through it. p = &y changes which object it points to.
  • Print addresses with static_cast<void*>(p) in std::println; they change between runs.
  • nullptr means "points to nothing". Check before dereferencing: dereferencing null is undefined behavior.
  • Uninitialized and dangling pointers can't be detected by looking at them. Initialize every pointer and never keep the address of an object that has died.
  • p->member is (*p).member. T** points to a pointer, used mainly by C APIs and argv.
  • Prefer references for "always an object", raw pointers for "maybe an object, not owned", and smart pointers for owned heap objects.

Next: Pointers and Arrays, where you'll move pointers through arrays with arithmetic and learn the one-past-the-end rule.