← Back to C++ Course | Chapter 7: Pointers & References | Lesson 3 of 11

C++ Modifying Values via Pointers

Assigning to a dereferenced pointer, *ptr = value, writes through the pointer to change the original variable's value, which is how functions modify their caller's data via pointer parameters.

Writing Through a Pointer

Assigning a new value to a dereferenced pointer, written *ptr = value, writes that value into the memory location the pointer refers to, changing the original variable.

Example: Writing Through a Pointer

cpp
#include <iostream>

int main() {
	int value = 5;
	int *ptr = &value;
	*ptr = 100;
	std::cout << value << std::endl;
	return 0;
}

Modifying with Arithmetic Through a Pointer

A dereferenced pointer can appear on either side of an arithmetic expression, letting the pointed-to value be read, modified, and written back in place, just like modifying a variable directly.

Example: Modifying with Arithmetic Through a Pointer

cpp
#include <iostream>

int main() {
	int value = 10;
	int *ptr = &value;
	*ptr = *ptr + 5;
	std::cout << value << std::endl;
	return 0;
}

Modifying a Variable Through a Function

A function that receives a pointer parameter can modify the caller's original variable by dereferencing and assigning to it, which is the classic C++ technique for pass-by-pointer.

Example: Modifying a Variable Through a Function

cpp
#include <iostream>

void setToZero(int *ptr) {
	*ptr = 0;
}

int main() {
	int value = 50;
	setToZero(&value);
	std::cout << value << std::endl;
	return 0;
}

Modifying Array Elements Through a Pointer

Since an array's name decays to a pointer to its first element, pointer arithmetic combined with dereferencing can be used to read and write individual array elements directly.

Example: Modifying Array Elements Through a Pointer

cpp
#include <iostream>

int main() {
	int arr[] = {1, 2, 3};
	int *ptr = arr;
	*(ptr + 1) = 99;
	std::cout << arr[1] << std::endl;
	return 0;
}

Modifying via a Pointer to a Struct

The -> operator combines dereferencing with member access, letting a struct's members be modified directly through a pointer to that struct.

Example: Modifying via a Pointer to a Struct

cpp
#include <iostream>

struct Point { int x; int y; };

int main() {
	Point p = {1, 2};
	Point *ptr = &p;
	ptr->x = 100;
	std::cout << p.x << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.