Lesson 7

Pointers

Short answer: a pointer is a variable that holds a memory address. &x gives you the address of x; *p gives you the value stored at the address p holds.

See an address

#include <iostream>
using namespace std;

int main() {
    int x = 42;
    int *p = &x;
    cout << "x = " << x << endl;
    cout << "*p = " << *p << endl;
    return 0;
}

p holds the address of x, so *p reads the same 42 through the pointer. The numeric address itself is not something you can print with cout in this browser engine — a real compiler prints it in hex.

Store it, read through it

#include <iostream>
using namespace std;

int main() {
    int x = 42;
    int *p = &x;      // p holds the address of x

    cout << *p << endl;   // 42 — read through the pointer
    *p = 99;              // write through the pointer
    cout << x << endl;    // 99 — x changed
    return 0;
}

That is the whole mechanism: p points at x, so writing through p writes to x. This is how one function can change another function's variable.

Why anyone needs this

To modify a caller's variable, pass its address:

#include <iostream>
using namespace std;

void doubleIt(int *p) {
    *p = *p * 2;
}

int main() {
    int n = 21;
    doubleIt(&n);
    cout << n << endl;   // 42
    return 0;
}

Because the argument is an address, the function changes the caller's n. Passing n by value would change only a copy. Full comparison of the three ways: value, pointer, reference.

Arrays and pointers are cousins

#include <iostream>
using namespace std;

int main() {
    int a[3] = {10, 20, 30};
    int *p = a;          // an array name decays to the address of its first element

    cout << *p << endl;       // 10
    cout << *(p + 1) << endl; // 20 — pointer arithmetic moves by elements
    return 0;
}

This is why arrays are "passed by reference" without you doing anything: what is passed is the first element's address.

The two rules

Pointers are why C++ has a reputation. In modern C++ most raw pointers are replaced by references and smart pointers — see the modern C++ roadmap for what to use instead.

Practice this lesson

These problems exercise exactly what you just read: