Loading lessons...
Introduction to Pointers
Introduction to Pointers
A pointer is a variable that stores a memory address. While a reference is a locked-in alias, a pointer is an ordinary variable you can inspect and even repoint.
Declaring a pointer
#include <string>
using namespace std;
string food = "Pizza";
string* ptr = &food;
string- thein the type tells youptris a pointer to a string.= &food- the&operator handsptrthe address offood.
Two symbols, two jobs
- The
instringis part of the type: "this variable is a pointer". - The
&in&foodis the address-of operator: "give me the address".
The position tells you which one you are looking at.
What a pointer holds
A pointer only stores a memory address. The address can come from &food, from new, or from nullptr (a pointer that points at nothing).
cout << ptr << endl; // a hexadecimal address, e.g. 0x7ffe0000a1c
Printing the pointer itself shows the address - not the value of food.
Pointer vs reference
string* ptr = &food; // pointer: stores an address
string& ref = food; // reference: another name for food
A reference is permanently glued to one variable. A pointer can be assigned a different address later.
TL;DR
- A pointer stores a memory address.
- It is declared with a
after the type:string ptr. - The
&operator provides the address of a variable. - Unlike a reference, a pointer can be repointed.