Lesson 116 +10 XP

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

Code

cpp
#include <string>
using namespace std;

string food = "Pizza";
string* ptr = &food;
  • string* - the * in the type tells you ptr is a pointer to a string.
  • = &amp;food - the &amp; operator hands ptr the address of food.

Two symbols, two jobs

  • The * in string* is part of the type: &quot;this variable is a pointer&quot;.
  • The &amp; in &amp;food is the address-of operator: &quot;give me the address&quot;.

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 &amp;food, from new, or from nullptr (a pointer that points at nothing).

Code

cpp
cout << ptr << endl;   // a hexadecimal address, e.g. 0x7ffe0000a1c

Printing the pointer itself shows the address - not the value of food.

Pointer vs reference

Code

cpp
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 &amp; operator provides the address of a variable.
  • Unlike a reference, a pointer can be repointed.