Core Module
12 min forge
C++ Memory Pointers
Advanced pointers, memory addresses, and arithmetic.
C++ Memory Pointers
π What is it
Pointers are variables that store memory addresses. In memory management, pointers are the primary way to interact with the heap. They allow for manual control over memory, which is a key feature of C++.
β‘ When to use
Use pointers for dynamic resource management, building custom data structures (Lists, Trees), and passing large objects efficiently.
π§ Time complexity
- Access/Dereference: $O(1)$
- Arithmetic: $O(1)$
π» Code example
cpp Standardint x = 10; int *p = &x; // x's address std::cout << *p; // 10 *p = 20; // x becomes 20
β Common mistakes
- Wild Pointers: Pointers that are not initialized to anything (not even
nullptr). - Memory Leaks: Losing the address of heap-allocated memory before freeing it.
- Arithmetic Errors: Incrementing a pointer by 1 moves it by
sizeof(type)bytes, not necessarily 1 byte.