← 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)
Ready to go further?

These free tutorials are a preview of what a Code Secure Academy cohort covers, project work and all.

Explore our tracks

Cookie preferences

Choose what you're comfortable with. You can change this any time from the footer.

Don't miss out

Ready to build something real?

Create a free account to enroll in a track, and get notified the moment a cohort opens.

Create free account