What A Pointer Is And Why It Exists
A normal variable like int x stores a value, and the program also places that value somewhere in memory. The name x is a convenient label the compiler lets you use so you can read and write that stored value without thinking about the physical location.
That location still matters because the CPU ultimately loads and stores using addresses. Even when you write x = 5;, the compiled code uses an address under the hood to find the bytes that belong to x and overwrite them.
From values to locations
A useful way to think about memory is as a long array of bytes, where each byte has an index called an address. When the compiler creates x, it chooses a region of addresses large enough to hold an int, then makes every use of the name x refer to that region.
Two consequences fall out of that model.
- If you change the value of
x, you overwrite bytes at the same address range. - If you create a second variable
y = x, you usually get a separate address range with a copied value, so later changes toxdo not affecty.
Pointers store addresses
A pointer is a variable whose value is an address. It does not store the int itself, it stores where an int lives in memory, so you can follow that address to access the int.
In C++, two operators make this concrete.
&x // address-of, produces the address where x is stored
*p // dereference, accesses the value stored at the address in p
Work through the memory boxes and how the value can change while the address stays the same.
Key invariant
Ifpequals&x, then*prefers to the same stored value asx.
Why real code uses pointers
Once you can store an address, you can share access to one object instead of copying it. That shows up in a few common situations.
- Sharing and mutation. If two parts of the program hold pointers to the same object, a write through one pointer changes what the other part observes.
- Optional data. A pointer can be
nullptrto mean no object, which makes absence explicit in the type. - Performance and size. Copying large objects is expensive, but copying a pointer is usually cheap because it is just an address value.
- Interoperability. Many C APIs and OS APIs pass data using pointers because they operate in terms of memory addresses.
Compare the copy versus share scenarios and watch how mutation and cost differ.
Sign up for free
Generate custom courses on any topic — with hands-on practice, AI guidance, and visuals built in.
Already have an account?