Thuta Learning
C++
IntermediateProgrammingBeginner

Pointers

C++Lesson 1430 min

What you'll walk away with

  • Declare a pointer with T*, take an address with & and dereference with * and ->
  • Re-aim a pointer at another object and use nullptr to mean "points at nothing"
  • Check for nullptr before dereferencing a pointer that may be empty
  • Tell const int* apart from int* const, and explain why a pointer to a local must not outlive it

Explain it simply

Explain it simply

Every variable lives somewhere in memory, and that location has a number called its address. A pointer is a variable whose value is such an address. Think of a contact card in your phone: the card is not your friend, it only tells you where to find them. Following the card to the real person is called dereferencing.

In C++, &food asks for the address of food, std::string* ptr declares a variable that can hold the address of a string, and *ptr means "the string at that address". Because ptr only stores a location, you can later point it at a different string, or at nothing at all with nullptr.

Problem → Why → Solution

The problem: a lookup that sometimes finds nothing

A function that searches for something has to report "not found" somehow. Returning a pointer is a common C++ way to do it: a pointer to the match, or nullptr when there is none. The bug appears when the caller forgets the second case. In the code below, findName() returns nullptr for an unknown name, and main dereferences it anyway. Dereferencing a null pointer is undefined behaviour, and on most systems the program simply crashes with a segmentation fault (an access violation on Windows).

lookup.cpp
#include <iostream>
#include <string>
#include <vector>

std::string* findName(std::vector<std::string>& names, const std::string& wanted) {
    for (std::string& name : names) {
        if (name == wanted) return &name;
    }
    return nullptr;                       // "not found"
}

int main() {
    std::vector<std::string> names{"Aye", "Bo"};
    std::string* match = findName(names, "Zaw");
    std::cout << match->size() << '\n';   // match is nullptr: crash
}

Why the compiler cannot save you here

Whether a pointer is null is a runtime fact: it depends on the data, not on the code, so the compiler accepts match->size() without complaint. A pointer that can be empty puts a duty on every caller: check for nullptr before using * or ->. The fix is one line, if (match != nullptr), and the rest of this lesson shows where else pointers can go stale.

Core concept: addresses, dereferencing and nullptr

A pointer type is written by adding * to the type it points at: int* points at an int, std::string* at a std::string. Two operators connect pointers and objects. The address-of operator & turns an object into its address (&food), and the dereference operator * turns an address back into the object it names (*ptr). When the object has members, ptr->size() is shorthand for (*ptr).size().

text
std::string* ptr = &food;
-------------------------
   ptr                        food
 +----------------+         +---------+
 | address of     | ------> | "Pizza" |
 | food           |         +---------+
 +----------------+

 *ptr        is food itself
 ptr->size() is food.size()
 ptr = &drink; moves the arrow, food is untouched

The * symbol has two jobs, which confuses many beginners. In a declaration such as std::string* ptr, it is part of the type and means "pointer to". In an expression such as *ptr = "Soup", it is the dereference operator and means "the object at this address". Read the line and ask yourself: am I declaring a variable or using one?

Unlike a reference, a pointer is a separate object with its own value, so it can change. Assigning ptr = &drink re-aims it at another string, and ptr = nullptr makes it point at nothing. nullptr is the C++11 null pointer literal; prefer it over 0 or the C macro NULL. Always initialise a pointer when you declare it: an uninitialised pointer holds garbage, and dereferencing it is undefined behaviour (GCC warns 'p' is used uninitialized).

Finally, a pointer is only as good as the object it points at. If that object is destroyed, for example a local variable whose function has returned, the pointer still holds the old address but now dangles. In modern C++ a raw pointer is used as an observer: it looks at an object owned by someone else, and it never deletes anything. Ownership belongs to containers and to the smart pointers covered in the coming lessons.

Mental model: a card that says where to look
  1. &x gives the address of x
  2. T* p stores that address
  3. *p and p-> reach the object itself
  4. nullptr means: points at nothing

Before every *p or p->, be sure of two things: p is not nullptr, and the object is still alive.

General pattern

cpp
Type value{};
Type* ptr = &value;           // ptr holds the address of value
*ptr = newValue;              // write through the pointer
ptr->member;                  // same as (*ptr).member
ptr = &otherValue;            // re-aim at another object
ptr = nullptr;                // points at nothing
if (ptr != nullptr) {         // check before dereferencing
    use(*ptr);
}
const Type* reader = &value;  // cannot modify value through reader

Type* is the pointer type, & produces an address and * follows it. Assigning to ptr changes where it points; assigning to *ptr changes the object it points at. A const on the left of * protects the object, not the pointer.

Example: one pointer, three targets

The program aims a pointer at a string, reads and changes the string through it, then re-aims it at a second string and finally at nothing. Notice that it never prints an address: addresses change from run to run because of address space layout randomisation, so comparing ptr == &food is the reliable way to show what the pointer holds.

pointers.cpp
#include <iostream>
#include <string>

void addTopping(std::string* order) {
    if (order == nullptr) {
        std::cout << "No order to update\n";
        return;
    }
    *order += " + cheese";
}

int main() {
    std::string food = "Pizza";
    std::string drink = "Tea";
    std::string* ptr = &food;

    std::cout << std::boolalpha;
    std::cout << "ptr holds the address of food: " << (ptr == &food) << '\n';
    std::cout << "Value through pointer: " << *ptr << '\n';

    addTopping(ptr);
    std::cout << "food is now: " << food << '\n';

    ptr = &drink;
    std::cout << "ptr now reads: " << *ptr << '\n';

    ptr = nullptr;
    addTopping(ptr);
}

Code breakdown

  1. Lines 4-8void addTopping(std::string* order) {

    The parameter is a pointer, so the function can change the caller's string. Because a pointer may be null, the first thing it does is check for nullptr and return early.

  2. Line 9*order += " + cheese";

    *order is the caller's string itself, so += appends to food, not to a copy.

  3. Line 15std::string* ptr = &food;

    &food produces the address of food, and ptr stores it. From here on, *ptr and food name the same object.

  4. Line 18(ptr == &food)

    Comparing addresses prints true or false, which is the same on every run, unlike the raw hexadecimal address.

  5. Line 24ptr = &drink;

    A pointer can be re-aimed. food is untouched; only the address stored in ptr changes, so *ptr now reads Tea.

  6. Lines 27-28ptr = nullptr;

    ptr now points at nothing. Passing it to addTopping() is safe only because the function checks for nullptr before dereferencing.

You should see
ptr holds the address of food: true
Value through pointer: Pizza
food is now: Pizza + cheese
ptr now reads: Tea
No order to update

const and pointers

const protects either the object or the pointer, depending on which side of the * it stands. Read the declaration from right to left: const int* reader is "a pointer to an int that is const", so you may re-aim it but not write through it. int* const fixed is "a const pointer to an int", so you may write through it but never re-aim it. Functions that only read through a pointer should take const T*.

const_pointers.cpp
#include <iostream>

int main() {
    int a = 1;
    int b = 2;

    const int* reader = &a;   // can move, cannot write through it
    reader = &b;              // OK: re-aim the pointer
    // *reader = 5;           // error: assignment of read-only location

    int* const fixed = &a;    // cannot move, can write through it
    *fixed = 10;              // OK: changes a
    // fixed = &b;            // error: assignment of read-only variable

    std::cout << *reader << ' ' << a << '\n';   // prints: 2 10
}
DeclarationRe-aim the pointer?Write through it?
const int* pyesno
int* const pnoyes
const int* const pnono

Pointers to elements inside a container

Pointers often point at objects inside a container, and -> calls a member function through the pointer. Such a pointer stays valid only while the container keeps that element where it is: a push_back() that makes a vector grow can move every element and leave the pointer dangling. Pointer arithmetic (p + 1) also exists for walking C arrays, but iterators, range-for and std::span do that job more safely.

element_pointer.cpp
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> names{"Aye", "Bo", "Chit"};
    std::string* second = &names[1];

    std::cout << *second << " has " << second->size() << " letters\n";
    second->append("bo");
    std::cout << names[1] << '\n';   // Bobo
}

In real projects

Where this shows up in real projects

Raw pointers are everywhere in real C++, but almost always in a non-owning role. A function that may or may not find something returns T* (or, in newer code, std::optional). A tree or graph node keeps a raw parent pointer that only looks back up. GUI frameworks such as Qt hand you pointers to widgets that the framework itself owns, and C libraries like SQLite, as well as operating system APIs, work through pointers to structures they manage.

Code that owns memory, on the other hand, rarely writes new and delete by hand any more. It uses std::vector, std::string and the smart pointers from the next lesson, and passes raw pointers or references down to functions that only need to look. Static analysers and sanitizers such as AddressSanitizer run routinely in CI to catch the null dereferences and dangling pointers that tests miss.

Common mistakes

Common mistakes

1. Dereferencing without a null check

When a function can return nullptr, every caller must test it before * or ->. match->size() on a null pointer is undefined behaviour and usually a crash. Write if (match != nullptr) { ... } or if (match) { ... }, and document which of your functions may return null.

2. Leaving a pointer uninitialised

int* p; *p = 5; writes to a random address. GCC flags it with 'p' is used uninitialized under -Wall, but only when it can prove it. Always start a pointer with a real address or nullptr: int* p = nullptr;.

3. Returning the address of a local variable

int* makeCounter() { int count = 0; return &count; } hands back the address of a variable that dies as the function returns. GCC warns address of local variable 'count' returned. Return the value itself, or return something whose lifetime is longer than the call.

4. Confusing ptr = with *ptr =

ptr = &drink changes where the pointer points; *ptr = "Tea" overwrites the object it points at. Mixing them up either changes the wrong variable or loses track of the object you meant to keep.

Best practices

Best practices

  • Initialise every pointer, with an address or nullptr, in the statement that declares it.
  • Use raw pointers to observe, never to own; let containers and smart pointers own memory.
  • Prefer a reference when the value can never be absent, and a pointer when "nothing" is a valid answer.
  • Take const T* when a function only reads through the pointer.

Mini challenge

Mini challenge: clean up sensor readings

A sensor sometimes reports negative readings that should be zero. Use pointers to find and fix them, then swap the first and last readings through pointers.

  • Write int* findFirstNegative(std::vector<int>& readings) that returns a pointer to the first negative element, or nullptr
  • In main, keep calling it and set *ptr = 0 until it returns nullptr, counting the fixes
  • Write void swapValues(int* a, int* b) that does nothing if either pointer is nullptr
  • Swap the first and last readings, then show that a call with nullptr is ignored
sensor.cpp
#include <iostream>
#include <vector>

int* findFirstNegative(std::vector<int>& readings) {
    // TODO: loop with int& so you can return the element's own address
    // TODO: return nullptr when nothing is negative
}

void swapValues(int* a, int* b) {
    // TODO: guard against nullptr, then swap *a and *b
}

void print(const std::vector<int>& readings) {
    // TODO: print every reading followed by a space, then a newline
}

int main() {
    std::vector<int> readings{12, -3, 7, -8, 5};
    // TODO: fix every negative reading, then print the count and the readings
    // TODO: swap the first and last readings, then try a swap with nullptr
}

Expected: The output should be: Fixed 2 readings: 12 0 7 0 5 After swap: 5 0 7 0 12 Null swap ignored: 5 0 7 0 12

Show hint

Loop with for (int& value : readings) and return &value, the address of the element itself; a copy's address would dangle. A for loop whose condition is bad != nullptr is a tidy way to repeat the search.

Show solution
sensor.cpp
#include <iostream>
#include <vector>

int* findFirstNegative(std::vector<int>& readings) {
    for (int& value : readings) {
        if (value < 0) return &value;
    }
    return nullptr;
}

void swapValues(int* a, int* b) {
    if (a == nullptr || b == nullptr) return;
    int temp = *a;
    *a = *b;
    *b = temp;
}

void print(const std::vector<int>& readings) {
    for (int value : readings) std::cout << value << ' ';
    std::cout << '\n';
}

int main() {
    std::vector<int> readings{12, -3, 7, -8, 5};

    int fixes = 0;
    for (int* bad = findFirstNegative(readings); bad != nullptr;
         bad = findFirstNegative(readings)) {
        *bad = 0;
        ++fixes;
    }
    std::cout << "Fixed " << fixes << " readings: ";
    print(readings);

    swapValues(&readings.front(), &readings.back());
    std::cout << "After swap: ";
    print(readings);

    swapValues(&readings[0], nullptr);
    std::cout << "Null swap ignored: ";
    print(readings);
}

Quick quiz 1 / 3

What does this print? int a = 1, b = 2; int* p = &a; p = &b; *p = 10; std::cout << a << ' ' << b;

Quick quiz 2 / 3

Which declaration allows *p = 5 but forbids p = &other?

Quick quiz 3 / 3

Why is int* makeCounter() { int count = 0; return &count; } a bug?

What to remember

  • A pointer stores an address: & takes it, * and -> follow it.
  • A pointer can be re-aimed or set to nullptr; check for nullptr before dereferencing.
  • const before * protects the object; const after * fixes the pointer.
  • A pointer dangles once its object dies; in modern C++ raw pointers observe and never own.

C++ Core Guidelines — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Pointers | Thuta Learning