Core Module
12 min forge
C++ Pointers Basics
Understanding addresses and pointers β the foundation of memory manipulation.
C++ Pointers Basics
π What is it
A pointer is a variable that stores the memory address of another variable. Pointers are one of the most powerful (and dangerous) features of C++.
β‘ When to use
For dynamic memory allocation, efficient data passing, and implementing complex data structures like Linked Lists and Trees.
π§ Time complexity
- Dereferencing: $O(1)$
- Address access: $O(1)$
π» Code example
cpp Standardint var = 20; int *ptr = &var; // ptr stores address of var std::cout << "Value: " << *ptr << std::endl; // Dereferencing: 20 std::cout << "Address: " << ptr << std::endl; // Address in hex
β Common mistakes
- Dangling Pointers: Pointing to memory that has been freed.
- Null Pointer Dereference: Trying to access value of a
nullptr. - Confusing the pointer address with the value it points to.