← C++ tutorial

C++

Pointers (Basics)

A pointer stores the memory address of another variable, rather than a value directly.

Example: a pointer to an int

#include <iostream>
using namespace std;

int main() {
    int age = 21;
    int* agePointer = &age;

    cout << "Value: " << *agePointer << endl;
    cout << "Address stored in pointer: " << agePointer << endl;
    return 0;
}
Value: 21
Address stored in pointer: 0x7ffeeb1c2a9c   (a real address differs every run)

Declare a pointer with * (int* agePointer;), and get a variable's address with &. Writing *agePointer (with the asterisk again) "follows" the pointer back to the actual value it points at — this is called dereferencing. Pointers are one of the things that give C++ its low-level control, and also one of the things that make it easy to make mistakes (following a pointer to memory that's no longer valid is a classic, hard-to-debug C++ bug) — most modern C++ code prefers safer alternatives like references and smart pointers where possible. This lesson is just the basic idea the rest builds on.

Example
#include <iostream>
using namespace std;

int main() {
    int age = 21;
    int* agePointer = &age;

    cout << "Value: " << *agePointer << endl;
    cout << "Address stored in pointer: " << agePointer << endl;
    return 0;
}
Output
Value: 21
Address stored in pointer: 0x7ffeeb1c2a9c   (a real address will differ each run)