Pointers in C++ allow direct memory access; modifying the value pointed to by a pointer also updates the original variable it references.
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
- The variable
motorcycleModelis initially"CBR600RR". - A pointer
ptris assigned to its memory address. *ptrretrieves the original value ("CBR600RR").- Modifying
*ptrupdatesmotorcycleModel, replacing"CBR600RR"with"Ducati Panigale V4". - Both
*ptrandmotorcycleModelnow reflect the new value.


