In C, a pointer is a variable that stores the memory address of an existing variable.
Note: Learn more about pointers in C++ here.
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.
#include <iostream>#include <string>using namespace std;int main() {// creating a variablestring name = "Pizza";// creating a pointer to the variablestring* ptr = &name;// printing the value of the variablecout << "This is the value of the variable: " << name << "\n";// obtaining and printing the memory adress of the variablecout <<"This is the memory adress of the variable: " << &name << "\n";// obtaining and printing the value of the variable using * operatorcout <<"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 pointercout << "This is the new pointer value: "<< *ptr << "\n";// printing the new value of the name variablecout << "This is the modified name of the variable: "<< name << "\n";return 0;}
name
and assign Theo
as its value.ptr
.name
.name
using the &
operator.name
using the dereference operator (*
).ptr
to David
.name
.