Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pointer
c++
communitycreator

How to modify a pointer value in C++

Onyejiaku Theophilus Chidalu

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;
}
Modifying a pointer value

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++
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring