C++ Modify Pointers

Pointers in C++ allow direct memory access, and modifying a pointer’s value also updates the original variable it references.

Tutorials dojo strip



Changing the Value Through a Pointer

Assigning a new value to a dereferenced pointer updates the original data.

Example: Updating a Variable via a Pointer

#include <iostream>
using namespace std;

int main() {
    string motorcycleModel = "CBR600RR";  
    string* ptr = &motorcycleModel;  

    // Output original value
    cout << motorcycleModel << "\n";  

    // Output memory address
    cout << &motorcycleModel << "\n";  

    // Output value using pointer
    cout << *ptr << "\n";  

    // Modify value through pointer
    *ptr = "Ducati Panigale V4";  

    // Output updated value using pointer
    cout << *ptr << "\n";  

    // Output updated value using variable
    cout << motorcycleModel << "\n";  

    return 0;
}

Output:

CBR600RR  
0x6dfed4  
CBR600RR  
Ducati Panigale V4  
Ducati Panigale V4  




How It Works

  1. The variable motorcycleModel is initially "CBR600RR".
  2. A pointer ptr is assigned to its memory address.
  3. *ptr retrieves the original value ("CBR600RR").
  4. Modifying *ptr updates motorcycleModel, replacing "CBR600RR" with "Ducati Panigale V4".
  5. Both *ptr and motorcycleModel now store the new value.
Tutorials dojo strip
Scroll to Top