Pointers

A pointer holds an address

A pointer is a variable whose value is an address. It “points” to another variable. You create one by putting * after the type:

#include <iostream>
using namespace std;

int main() {
    int score = 50;
    int* ptr = &score;       // ptr holds the address of score

    cout << "score:  " << score << "\n";
    cout << "*ptr:   " << *ptr << "\n";   // follow the pointer: the value at that address
    return 0;
}

Output

score:  50
*ptr:   50
  • int* ptr – ptr is a pointer to an int.
  • &score – the address of score.
  • *ptr – go to the address and use the value there. This is called dereferencing.

Think of it like this: A pointer is a piece of paper with a house number written on it. *ptr means “walk to that house and look inside”.

Changing a value through a pointer

#include <iostream>
using namespace std;

int main() {
    int score = 50;
    int* ptr = &score;
    *ptr = 99;                 // change what ptr points to
    cout << "score is now " << score << "\n";
    *ptr += 1;
    cout << "score is now " << score << "\n";
    return 0;
}

Output

score is now 99
score is now 100

Pointing somewhere else

#include <iostream>
using namespace std;

int main() {
    int a = 1, b = 2;
    int* p = &a;
    cout << *p << "\n";
    p = &b;                    // now p points to b
    cout << *p << "\n";
    return 0;
}

Output

1
2

nullptr: pointing at nothing

A pointer that doesn't point anywhere yet should be set to nullptr. Always check before you follow it:

#include <iostream>
using namespace std;

int main() {
    int* p = nullptr;
    if (p == nullptr) {
        cout << "p points to nothing yet\n";
    }
    int value = 7;
    p = &value;
    if (p != nullptr) {
        cout << "p points to " << *p << "\n";
    }
    return 0;
}

Output

p points to nothing yet
p points to 7

Common mistake: Following a nullptr or an uninitialised pointer (*p when p points nowhere) crashes the program, or worse. Always give pointers a value, and check for nullptr.

SymbolIn a typeIn front of a variable
*int* p: p is a pointer*p: the value p points to
&int& r: r is a reference&x: the address of x
HOME LABS COMMUNITY DASHBOARD