Pointers
Overview
If the & operator allows us to find a memory address, a Pointer is a special type of variable engineered specifically to store a memory address.
Think of a Pointer like a treasure map. The map itself isn't the gold; it just tells you exactly where the gold is buried. Pointers are the most infamous, powerful, and dangerous feature in C++. They allow you to dynamically pass massive objects between functions without copying them, build complex data structures like Linked Lists, and control the hardware directly.
Syntax
int score = 100;
// 1. Declare a Pointer
// The asterisk (*) indicates that 'ptr' holds a memory address pointing to an int.
int* ptr;
// 2. Initialize the Pointer
// We store the physical address of 'score' inside the pointer.
ptr = &score;
// Now, 'ptr' holds a value like 0x7ffe4
// And 'score' holds the value 100Common Pitfalls
- Uninitialized Pointers (Wild Pointers). If you write
int* ptr;but forget to assign it an address, it doesn't default to empty. It points to a completely random address in RAM. If you try to write data to that random address, your program will instantly crash with a 'Segmentation Fault'. - Type Mismatch. You cannot point a
double*at anint. Pointers must strictly match the data type they are pointing to so the compiler knows how many bytes to read.
Interview Questions
The size of a pointer relies entirely on the CPU Architecture, not the data type it points to. On a 32-bit operating system, every pointer is exactly 4 bytes. On a modern 64-bit operating system, every single pointer (whether it's an int*, a double*, or a MassiveGameObject*) is exactly 8 bytes.
Real-World Example
Using pointers to create an alias, allowing us to interact with the original variable from a completely different scope.
#include <iostream>
int main() {
int playerHealth = 100;
// We create a pointer holding the address of playerHealth
int* healthPtr = &playerHealth;
std::cout << "Memory Address: " << healthPtr << "\n";
return 0;
}Check Your Knowledge
Test your understanding of Pointers with these quick questions.