C++ Pointers
A pointer is a variable that stores the memory address of another variable, declared with `*`. The `&` operator gets a variable's address, and `*` dereferences a pointer to access the value it points to.
Pointers are powerful but dangerous โ dereferencing a null or dangling pointer causes undefined behaviour, often a crash.
Declaring and dereferencing
`int x = 5; int* p = &x;` makes p store x's address. `*p` reads or writes the value at that address โ `*p = 10;` changes x to 10.
Null pointers
A pointer with no valid target should be set to `nullptr` (C++11). Always check `if (p != nullptr)` before dereferencing.
int x = 5;
int* p = &x;
*p = 10;
std::cout << x;10Dereferencing p and assigning changes x directly.
int x = 42;
int* p = &x;
std::cout << *p;42*p reads the value stored at the address p points to.
Key points
- A pointer stores a memory address, declared with *.
- & gets the address of a variable.
- * dereferences a pointer to get/set its target value.
- Uninitialised or dangling pointers should be set to nullptr.
