Lesson 119 +10 XP

Modify Pointers

Modify Pointers

Three ways to change things with a pointer: change the value it points at, change where it points, and compare pointers.

Change the value through the pointer

#include <string>
using namespace std;

string food = "Pizza";
string* ptr = &food;
*ptr = "Sushi";        // write through the pointer

cout << food << endl;   // Sushi

Assigning to *ptr changes the object it points to - which here is food.

Repoint the pointer

string drink = "Cola";
string* ptr = &food;

ptr = &drink;           // now the pointer points to drink
cout << *ptr << endl;   // Cola

A pointer is just a variable holding an address, so you can store a different address in it later. A reference cannot do that - it is bound at declaration.

Comparing pointers

int a = 1, b = 1;
int* p = &a;
int* q = &b;

if (p == q) { }        // compare the addresses
if (*p == *q) { }      // compare the values
  • p == q asks: do both pointers point to the same address?
  • p == q asks: are the pointed-to values equal?

TL;DR

  • *ptr = value writes through the pointer.
  • ptr = &other re-points the pointer.
  • p == q compares addresses; p == q compares values.
  • Only a pointer can be re-pointed - not a reference.