Introduction to Pointers
A friendly first look at memory addresses and the & and * operators
- explain what a memory address is,
- use
&to get the address of a variable, - declare a pointer and use
*to read or change the value it points to, - say why pointers matter in C++.
1. What is a memory address?
Think of the computer's memory as a very long street of tiny houses. Each house can hold one piece of data, and each house has its own number so it can be found. That house number is called a memory address.
When you write int age = 25;, the computer picks a free house, writes 25 inside it, and remembers its address for you. You normally use the name age, but underneath there is always an address doing the real work.
25 is a friend living in a house. The address is that house's street number. If you know the number, you can always find your friend.2. The & operator: "address of"
To ask "where does this variable live?", put the address-of operator & in front of it. &age means "the address of age".
#include <iostream>
using namespace std;
int main() {
int age = 25;
cout << "Value: " << age << endl;
cout << "Address: " << &age << endl;
return 0;
}
Expected output:
Value: 25
Address: 0x7ffee3b2c9ac
The exact address (that long 0x... number) changes each time you run the program — that is normal. What matters is that &age gives you the address, while plain age gives you the value.