Courses/C++/Pointers & References

    Lesson 8 • Intermediate

    Pointers & References

    Master memory addresses, pointer arithmetic, and references — the features that make C++ uniquely powerful.

    What You'll Learn

    • Pointers, addresses, and dereferencing
    • Pointer arithmetic and arrays
    • References as aliases
    • Smart pointers preview (unique_ptr, shared_ptr)

    Understanding Pointers

    Every variable lives at a specific memory address. A pointer is a variable that stores that address instead of a direct value.

    Think of it like a house address. The house (variable) holds your stuff (value). A pointer is a note card with the house address written on it — it doesn't hold your stuff directly, but it tells you exactly where to find it.

    int x = 42;       // x holds the value 42
    int* ptr = &x;    // ptr holds the ADDRESS of x
    
    cout << x;        // 42 (the value)
    cout << &x;       // 0x7ff... (address of x)
    cout << ptr;      // 0x7ff... (same address)
    cout << *ptr;     // 42 (dereference — get value AT address)
    OperatorNamePurpose
    &Address-ofGets the memory address of a variable
    *DereferenceAccesses the value at the address
    nullptrNull pointerA pointer that points to nothing

    Pointer Basics

    Create pointers, dereference values, and check null pointers

    Try it Yourself »
    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        int age = 25;
        
        // & = "address of" operator
        cout << "Value of age: " << age << endl;
        cout << "Address of age: " << &age << endl;
        
        // Pointer declaration: type* name = &variable
        int* ptr = &age;
        
        cout << "\n=== Pointer Details ===" << endl;
        cout << "ptr (address stored): " << ptr << endl;
        cout << "*ptr (dereferenced value): " << *ptr << endl;
        
        // Modifying through a pointer
        *ptr = 30
    ...

    Pointer Arithmetic

    Navigate arrays with pointer math and reverse an array using two pointers

    Try it Yourself »
    C++
    #include <iostream>
    using namespace std;
    
    int main() {
        // Arrays and pointers are closely related
        int arr[] = {10, 20, 30, 40, 50};
        int* ptr = arr;  // Array name = pointer to first element
        
        cout << "=== Pointer Arithmetic ===" << endl;
        cout << "*ptr (arr[0]): " << *ptr << endl;
        cout << "*(ptr+1) (arr[1]): " << *(ptr + 1) << endl;
        cout << "*(ptr+2) (arr[2]): " << *(ptr + 2) << endl;
        
        // Iterating with pointer arithmetic
        cout << "\n=== Array via Pointer
    ...

    References — Safer Aliases

    A reference is an alias (alternative name) for an existing variable. Unlike pointers, references must be initialized, can't be null, and can't be reassigned to refer to a different variable.

    FeaturePointerReference
    Can be null✅ Yes❌ No
    Can be reassigned✅ Yes❌ No
    Must initialize❌ No✅ Yes
    Syntaxint* p = &x;int& r = x;
    Access value*pr (automatic)

    References vs Pointers

    Compare swap implementations and use reference returns

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Swap using references (clean syntax)
    void swap(int &a, int &b) {
        int temp = a;
        a = b;
        b = temp;
    }
    
    // Swap using pointers (explicit, more flexible)
    void swapPtr(int* a, int* b) {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    
    // Return reference to allow chaining
    int& getElement(int arr[], int index) {
        return arr[index];
    }
    
    int main() {
        // Reference basics
        int original = 42;
        int& ref = original;  // ref
    ...

    Smart Pointers Preview

    See unique_ptr and shared_ptr for automatic memory management

    Try it Yourself »
    C++
    #include <iostream>
    #include <memory>
    using namespace std;
    
    class Player {
    public:
        string name;
        int health;
        
        Player(string n, int h) : name(n), health(h) {
            cout << name << " created!" << endl;
        }
        
        ~Player() {
            cout << name << " destroyed!" << endl;
        }
        
        void takeDamage(int dmg) {
            health -= dmg;
            cout << name << " took " << dmg << " damage. HP: " << health << endl;
        }
    };
    
    int main() {
        // RAW pointer (manual memory managemen
    ...

    Common Mistakes

    ⚠️ Dereferencing null: *nullptr causes a crash. Always check for null before dereferencing.

    ⚠️ Dangling pointers: A pointer to a deleted or out-of-scope variable contains garbage data.

    ⚠️ Forgetting * in declaration: int *a, b; — only a is a pointer, b is a regular int.

    ⚠️ Uninitialized pointers: Wild pointers point to random memory. Always initialize to nullptr or a valid address.

    Pro Tips

    💡 Prefer references over pointers: When you don't need null or reassignment, references are safer and cleaner.

    💡 Use smart pointers: In modern C++, unique_ptr and shared_ptr should replace raw new/delete.

    💡 const correctness: Use const int* when you don't need to modify the pointed-to value.

    Lesson Complete!

    You now understand pointers, references, and how C++ manages memory at a low level. Next up: Object-Oriented Programming — organize code with classes and objects.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service