Memory Addresses
Overview
To master C++, you must understand how a computer physically stores data. Your computer's RAM is fundamentally a massive street of microscopic houses, each holding 1 byte of data. Just like a real house, every single byte in RAM has a unique, absolute 'Memory Address' (usually represented as a hexadecimal number like 0x7ffe4).
When you declare int score = 100;, the C++ compiler automatically finds an empty house, locks down 4 bytes (since an int is 4 bytes), and stores the number 100 there. You can physically see the exact hexadecimal address where your data lives by using the Address-Of Operator (`&`).
Syntax
#include <iostream>
int main() {
int score = 100;
// 1. Printing the Value
std::cout << "Value: " << score << "\n"; // 100
// 2. Printing the Memory Address
// The '&' operator asks: "Where is this stored in RAM?"
std::cout << "Address: " << &score << "\n"; // E.g., 0x7ffee613a8ac
return 0;
}Common Pitfalls
- Assuming memory addresses are static. If you run your program,
&scoremight print0x1A2B. If you close the program and run it again, it will almost certainly print a completely different address. The Operating System dynamically assigns RAM based on what is available at that exact millisecond.
Interview Questions
C++ was designed for systems programming (Operating Systems, Game Engines, Drivers). Direct memory access allows C++ developers to tightly pack data into CPU Caches, write custom memory allocators, and interface directly with hardware registers (like writing a byte directly to a GPU memory address) at blazing speeds.
Real-World Example
Proving that an array is stored in contiguous (side-by-side) memory blocks by printing the address of each element.
#include <iostream>
int main() {
int arr[3] = {10, 20, 30};
// Because an 'int' is 4 bytes, you will see the hexadecimal
// addresses jump by exactly 4 bytes each time!
for(int i = 0; i < 3; i++) {
std::cout << "Index " << i << " Address: " << &arr[i] << "\n";
}
return 0;
}Check Your Knowledge
Test your understanding of Memory Addresses with these quick questions.