C++ Modify Pointers

Dereferencing does not just let you read a value; it also lets you change it. Because a pointer holds the address of a variable, writing through the pointer updates the original variable directly.

Changing a Value Through a Pointer

To change the value at the address a pointer holds, dereference the pointer with a star (*) and assign a new value. This reaches through the pointer and modifies the original variable.

Writing through a pointer

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Pizza";
  string* ptr = &food;
  *ptr = "Hamburger";   // change the value via the pointer
  cout << *ptr << "\n"; // Hamburger
  cout << food;         // the original also changed
  return 0;
}
// Output:
// Hamburger
// Hamburger

Both Names See the Change

Since the pointer and the variable refer to the same memory, a change made through the pointer is visible through the variable, and the other way around. There is only one value; it just has two ways to reach it.

Updating a number in place

#include <iostream>
using namespace std;

int main() {
  int count = 10;
  int* ptr = &count;
  *ptr = *ptr + 5;   // add 5 through the pointer
  cout << count;     // the variable now holds 15
  return 0;
}
// Output: 15

Reassigning the Pointer Itself

There is a difference between changing the value a pointer points to and changing where the pointer points. Writing *ptr = ... changes the value, while writing ptr = &other makes the pointer point to a different variable entirely.

StatementWhat it does
*ptr = 20;Changes the value at the current address
ptr = &other;Points the pointer at a different variable
  • Use *ptr = value to modify the data the pointer refers to.
  • Use ptr = &variable to make the pointer refer to something else.
  • Only one value exists, so changes through the pointer affect the original.
Note: This ability to modify the caller's data is exactly why pointers and references are used to pass variables into functions that need to change them.