Pointer
Programming
Pointers are variables that store memory addresses of other variables. They are fundamental to C++ and enable dynamic memory allocation, efficient parameter passing, and low-level memory manipulation.
Basic Usage
#include <iostream>
int main() {
int x = 10;
int* ptr = &x;
std::cout << "Value of x: " << x << std::endl;
std::cout << "Address of x: " << ptr << std::endl;
std::cout << "Value at address: " << *ptr << std::endl;
return 0;
} Key Concepts
- Pointer Declaration:
int* ptrdeclares a pointer to an integer - Address-of Operator:
&xgets the memory address of variablex - Dereference Operator:
*ptraccesses the value at the address stored inptr
Pointer Operations
Pointers support arithmetic operations and can be used to modify values indirectly:
#include <iostream>
int main() {
int x = 10;
int* ptr = &x;
// Modify value through pointer
*ptr = 20;
std::cout << "x after modification: " << x << std::endl;
// Pointer arithmetic
int arr[5] = {1, 2, 3, 4, 5};
int* p = arr; // Points to first element
std::cout << "First element: " << *p << std::endl;
std::cout << "Second element: " << *(p + 1) << std::endl;
return 0;
} Dynamic Memory Allocation
Pointers are essential for dynamic memory allocation:
#include <iostream>
int main() {
// Allocate memory dynamically
int* ptr = new int(42);
std::cout << "Value: " << *ptr << std::endl;
// Always deallocate to prevent memory leaks
delete ptr;
ptr = nullptr; // Good practice: set to nullptr after deletion
return 0;
} Common Pitfalls
- Dangling Pointers: Using a pointer after the object it points to has been destroyed
- Memory Leaks: Forgetting to
deletedynamically allocated memory - Null Pointer Dereference: Dereferencing a
nullptrcauses undefined behavior - Uninitialized Pointers: Always initialize pointers to avoid undefined behavior
Best Practices
- Prefer smart pointers (
std::unique_ptr,std::shared_ptr) over raw pointers when possible - Initialize pointers to
nullptrif not immediately assigned - Always pair
newwithdeleteandnew[]withdelete[] - Set pointers to
nullptrafter deletion - Use references when you don't need pointer semantics (nullability, reassignment)
Pointer vs Reference
References are safer alternatives when you don't need pointer features:
- References: Must be initialized, cannot be reassigned, cannot be null
- Pointers: Can be null, can be reassigned, support arithmetic
Output
Value of x: 10
Address of x: 0x7fff5fbff6ac
Value at address: 10 Note: The actual memory address will vary each time the program runs.