Memory, Addresses, and the & Operator
What memory actually is
When your compiled program runs, the operating system hands it a big block of memory to work with, called RAM (random access memory). You can think of RAM as an enormous row of numbered storage slots, each one holding a single byte (8 bits) of data. The number attached to each slot is called its memory address.
That’s really it. A computer’s memory is just billions of these numbered slots, and when you declare a variable, the compiler reserves as many of them as its type needs.
A variable is a name for an address
When you write:
int steps = 8200;two things happen. The compiler sets aside enough memory to hold an int (usually 4 bytes), and then it associates the name steps with the address where that memory starts.
steps just becomes a label for that memory address. From then on, whenever your code says steps, the compiler quietly translates that into “go to this address and read (or write) the value stored there.”
Finding an address with &
C++ lets you access that address directly, using the address-of operator, written as &.
Running this prints something like:
Value of steps: 8200
Address of steps: 0x7ffee2a1c05cThat second line is the address, shown in hexadecimal (base 16, the usual way addresses are displayed). This number is a real location in your computer’s memory, where steps‘s 4 bytes are stored during this run of the program.
Note that this operator only works on variables that actually occupy memory, and not on literals.
Different variables, different addresses
Every variable gets its own address, and you can see this directly:
The compiler is free to place variables in memory wherever it finds convenient.
Addresses change every time you run the program
If you run the same program twice, you may get different addresses each time. That’s by design. Modern operating systems deliberately shuffle where a program’s memory gets placed, partly for security reasons (it makes certain attacks harder), and partly because the exact memory available varies run to run anyway.