devnotes.

Pointers in C++

Pointers in C++ work exactly as they do in C, with new/delete replacing malloc/free as the idiomatic way to manage heap memory.

int age = 25;
int *ptr = &age;

std::cout << *ptr << "\n";   // 25 — dereference
*ptr = 30;                     // modifies age through the pointer

int *heapValue = new int(42); // allocate on the heap
std::cout << *heapValue << "\n";
delete heapValue;              // must free manually — new always pairs with delete
heapValue = nullptr;           // avoid a dangling pointer

int *arr = new int[5];         // allocate an array on the heap
delete[] arr;                  // array allocations need delete[], not delete

Every rule from C pointers still applies: & takes an address, * dereferences, an uninitialized pointer is dangerous, and a pointer that's been deleted should immediately be set to nullptr. The one hard rule specific to C++: memory allocated with new must be freed with delete, and memory allocated with new[] (an array) must be freed with delete[] — mismatching them (delete on a new[] allocation, or vice versa) is undefined behavior.

In practice, modern C++ code reaches for raw new/delete far less often than C reaches for malloc/free, because smart pointers (std::unique_ptr, std::shared_ptr, covered in the Memory Management chapter) and standard containers (std::vector instead of a manually-managed array) handle allocation and deallocation automatically — but understanding raw pointers first is essential, since smart pointers and containers are built directly on top of them.

Pointers in C++: new, delete, and delete[] | DevNotes