Open In App

C++ Modify Pointers

Last Updated : 05 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Pointer in C++

Pointers are an essential part of the C++ language. It allows us to store the memory address of a variable. One thing to note here is that if we change the value that a pointer is pointing to, then the value of the original variable also changes. Now, let’s check the approach we are going to use.

Approach:

In the below example, we will first declare and initialize a string variable. Then, we will store the address of the string variable in a pointer. Finally, we will modify the value that the pointer is pointing to and print all the values associated with the program to the screen.

Example:

C++




// C++ program to demonstrate the
// process of modifying a pointer
#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
    string website = "ABC";
 
    string* p = &website;
 
    cout << "The value of the variable: " << website
         << "\n";
 
    cout << "The memory address of the variable: " << p
         << "\n";
 
    cout << "The value that the pointer is pointing to: "
         << *p << "\n";
 
    *p = "GeeksforGeeks";
 
    cout
        << "The new value that the pointer is pointing to: "
        << *p << "\n";
 
    cout << "The memory address of the variable: " << p
         << "\n";
 
    cout << "The new value of the variable: " << website
         << "\n";
 
    return 0;
}


Output

The value of the variable: ABC
The memory address of the variable: 0x7ffef00579f0
The value that the pointer is pointing to: ABC
The new value that the pointer is pointing to: GeeksforGeeks
The memory address of the variable: 0x7ffef00579f0
The new value of the variable: GeeksforGeeks

In the above output, we can see that the value the pointer was pointing to changed from ABC to GeeksforGeeks. Consequently, the value of the website variable also changed from ABC to GeeksforGeeks. And, this doesn’t affect the address of the website just changes the value inside it.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads