Pointers in C++ allow direct memory access, and modifying a pointer’s value 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
motorcycleModel
is initially"CBR600RR"
. - A pointer
ptr
is assigned to its memory address. *ptr
retrieves the original value ("CBR600RR"
).- Modifying
*ptr
updatesmotorcycleModel
, replacing"CBR600RR"
with"Ducati Panigale V4"
. - Both
*ptr
andmotorcycleModel
now store the new value.