Lesson 11 of 25

Pointers

Pointer Basics

A pointer is a variable that stores the memory address of another variable. Pointers are fundamental to C++ and enable dynamic memory, data structures, and efficient code.

Example
int value = 42;
int* ptr = &value;  // ptr holds the address of value

cout << value << endl;   // 42 (the value)
cout << &value << endl;  // 0x7fff... (address of value)
cout << ptr << endl;     // same address
cout << *ptr << endl;    // 42 (dereference — get value at address)

// Modify through pointer
*ptr = 100;
cout << value << endl;  // 100

// Null pointer
int* empty = nullptr;  // points to nothing
if (empty == nullptr) {
    cout << "Pointer is null" << endl;
}

Dynamic Memory

Use new to allocate memory on the heap and delete to free it. For modern C++, prefer smart pointers.

Example
// Dynamic allocation
int* num = new int(42);
cout << *num << endl;  // 42
delete num;            // free memory

// Dynamic array
int* arr = new int[5]{10, 20, 30, 40, 50};
cout << arr[2] << endl;  // 30
delete[] arr;             // free array memory

// Smart pointers (C++11) — automatic memory management
#include <memory>

unique_ptr<int> uptr = make_unique<int>(42);
cout << *uptr << endl;  // 42
// No need to delete — freed automatically

shared_ptr<int> sptr = make_shared<int>(100);
cout << *sptr << endl;  // 100