C++ Pointers in a Nutshell
Pointers are one of the most confusing elements of C++ language. So I wanted to give a brief explanation.
Let’s start by defining two variables.
int x = 5;
int y = x;
So here we defined an integer x and assigned value of 5 to it. Then we defined y and assigned x as the value of it. So now we have two variables which have different memory locations. They both have the same value.
In C++, there is another type called pointer which does not carry the value but points the address of value by the memory location.
Let’s define a pointer now.
int* ptr;
This line defines a pointer named ptr and it is a pointer of int.
Now let’s define the address of x to this pointer.
ptr = &x;
Ptr now holds the address of x. Now let’s define another line to use the address that our pointer holds.
y = *ptr;
Now when we print the value of y we expect to see value 5 since we assigned the value that is held by the address our pointer points.
An Example:
int main()
{
int x {12};
int y {3456};
int* ptr = &x;
std::cout << *ptr << std::endl;
x = 789;
std::cout << *ptr << std::endl;
ptr = &y;
std::cout << *ptr << std::endl;
return 0;
}
This program will output
12
789
3456
The asterisk (*) de-references the pointer to the value it points and we see the correct values after each update.