Lesson 116 +10 XP

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 - the in the type tells you ptr is a pointer to a string.
  • = &food - the & operator hands ptr the address of food.

Two symbols, two jobs

  • The in string is part of the type: "this variable is a pointer".
  • The & in &food is 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.