Pointers are often considered the "boss level" of C++ basics. While they can be confusing at first, they are what make C++ so powerful for game engines and operating systems.
A Pointer is a variable that stores the memory address of another variable. Instead of holding a value (like 10), it holds the "house address" where that 10 lives.
1. Two Key Operators
Address-of Operator (
&): Used to get the memory address of a variable.Dereference Operator (
*): Used to "go to" the address and see (or change) the value stored there.
2. Why use Pointers?
Efficiency: You can pass large amounts of data to functions without copying them.
Dynamic Memory: You can request memory while the program is running (useful for things like "open world" games where objects load/unload).
Hardware Access: You can talk directly to specific memory locations.
Code Example: Pointing and Dereferencing
This program shows how to create a pointer, view an address, and change a value remotely.
#include <iostream>
using namespace std;
int main() {
int goldCoins = 50;
// 1. Declare a pointer
// The '*' here tells C++ 'ptr' is a pointer that holds an int address
int* ptr = &goldCoins;
cout << "Value of goldCoins: " << goldCoins << endl;
// 2. See the memory address (will look like 0x7ffd...)
cout << "Memory address of goldCoins: " << &goldCoins << endl;
cout << "Value stored in ptr: " << ptr << endl;
// 3. Dereferencing (Accessing value via the pointer)
// The '*' here means "value at the address"
cout << "Value pointed to by ptr: " << *ptr << endl;
// 4. Changing the value through the pointer
*ptr = 100;
cout << "New value of goldCoins: " << goldCoins << endl;
return 0;
}3. Null Pointers
Always initialize your pointers. If you don't have an address to give it yet, use nullptr: int* p = nullptr; This prevents the pointer from pointing to a random, dangerous location in memory.
Crucial Distinction:
int* ptr-> I am creating a pointer.ptr-> The address itself.*ptr-> The value inside that address.