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 variable string name = "Pizza"; // creating a pointer to the variable string* ptr = &name; // printing the value of the variable cout << "This is the value of the variable: " << name << "\n"; // obtaining and printing the memory adress of the variable cout <<"This is the memory adress of the variable: " << &name << "\n"; // obtaining and printing the value of the variable using * operator cout <<"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 pointer cout << "This is the new pointer value: "<< *ptr << "\n"; // printing the new value of the name variable cout << "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
.RELATED TAGS
CONTRIBUTOR
View all Courses