What Is a Pointer?
In C++, a pointer is a variable that stores a memory address. Every variable in your program occupies some location in memory, and a pointer simply holds that address.
Declaring and Using Pointers
int x = 42; // x lives at some address, say 0x7ffd42
int* ptr = &x; // ptr stores the address of x (&x)
std::cout << *ptr; // prints 42 (* dereferences the pointer)&x— the address-of operator, returns the memory address ofx*ptr— the dereference operator, reads the value at the address stored inptrint* ptr— declaresptras a pointer to anint
Pointer Arithmetic
Pointers support arithmetic. Adding 1 to a pointer moves it by sizeof(int) bytes (usually 4):
int arr[] = {10, 20, 30};
int* p = arr; // points to arr[0]
std::cout << *p; // 10
p++; // now points to arr[1]
std::cout << *p; // 20This is exactly how array indexing works under the hood: arr[i] is equivalent to *(arr + i).
Null Pointers
A null pointer points to nothing — it's the pointer equivalent of zero:
int* p = nullptr; // C++11 and later
if (p != nullptr) {
// safe to dereference
}Never dereference a null or uninitialized pointer — it causes undefined behavior (usually a segfault).