Topic 37 of 83
Memory Addresses
Overview
Every variable in C++ is stored in a specific location in RAM, identified by a unique memory address (hexadecimal). The address-of operator `&` retrieves this address.
Syntax
cpp
int x = 42;
// Print the value
cout << x;
// Print the memory address where x is stored
cout << &x; // outputs something like 0x7ffeefbff5ecCommon Pitfalls
- Trying to assign a memory address to a standard integer variable. Addresses must be stored in pointers.
Interview Tips
- Explain that memory addresses are usually represented in hexadecimal format. Pointers are simply variables that hold these hexadecimal addresses.
Real-World Example
Viewing the actual RAM addresses of variables.
example
cpp
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout << "Value of a: " << a << ", Address: " << &a << endl;
cout << "Value of b: " << b << ", Address: " << &b << endl;
return 0;
}