How to modify a pointer value in C++
Overview
In C, a pointer is a variable that stores the memory address of an existing variable.
Note: Learn more about pointers in C++ here.
Modifying the value of a pointer
We can change the pointer’s value in a code, but the downside is that the changes made also cause a change in the original variable.
Example
#include <iostream>#include <string>using namespace std;int main() {// creating a variablestring name = "Pizza";// creating a pointer to the variablestring* ptr = &name;// printing the value of the variablecout << "This is the value of the variable: " << name << "\n";// obtaining and printing the memory adress of the variablecout <<"This is the memory adress of the variable: " << &name << "\n";// obtaining and printing the value of the variable using * operatorcout <<"This is also the value of the variable: "<< *ptr << "\n";// Changing the value of the pointer*ptr = "David";// obtaining and printing the new value of the pointercout << "This is the new pointer value: "<< *ptr << "\n";// printing the new value of the name variablecout << "This is the modified name of the variable: "<< name << "\n";return 0;}
Explanation
- Line 7: We create a variable
nameand assignTheoas its value. - Line 10: We create a pointer to the variable
ptr. - Line 13: We print the value of the variable
name. - Line 16: We obtain and print the memory address of the variable
nameusing the&operator. - Line 19: We obtain and print the value of the variable
nameusing the dereference operator (*). - Line 22: We change the value of the pointer
ptrtoDavid. - Line 25: We obtain and print the new value of the pointer.
- Line 28: We print the modified variable
name.