C++ Modifying Values via Pointers
In this page:
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
#include <iostream>
int main() {
int value = 5;
int *ptr = &value;
*ptr = 100;
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
int value = 10;
int *ptr = &value;
*ptr = *ptr + 5;
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
void setToZero(int *ptr) {
*ptr = 0;
}
int main() {
int value = 50;
setToZero(&value);
std::cout << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
int main() {
int arr[] = {1, 2, 3};
int *ptr = arr;
*(ptr + 1) = 99;
std::cout << arr[1] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: