Loading lessons...
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 == qasks: do both pointers point to the same address?p == qasks: are the pointed-to values equal?
TL;DR
*ptr = valuewrites through the pointer.ptr = &otherre-points the pointer.p == qcompares addresses;p == qcompares values.- Only a pointer can be re-pointed - not a reference.