Trusted answers to developer questions

How to modify a pointer value in C++

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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 variable
string name = "Pizza";
// creating a pointer to the variable
string* ptr = &name;
// printing the value of the variable
cout << "This is the value of the variable: " << name << "\n";
// obtaining and printing the memory adress of the variable
cout <<"This is the memory adress of the variable: " << &name << "\n";
// obtaining and printing the value of the variable using * operator
cout <<"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 pointer
cout << "This is the new pointer value: "<< *ptr << "\n";
// printing the new value of the name variable
cout << "This is the modified name of the variable: "<< name << "\n";
return 0;
}

Explanation

  • Line 7: We create a variable name and assign Theo as 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 name using the & operator.
  • Line 19: We obtain and print the value of the variable name using the dereference operator (*).
  • Line 22: We change the value of the pointer ptr to David.
  • Line 25: We obtain and print the new value of the pointer.
  • Line 28: We print the modified variable name.

RELATED TAGS

pointer
c++

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
Did you find this helpful?