Where’s your seat?
“F5” he said.
Just like how the seats in a theatre are identified by their locations, similarly variables also can be identified by their locations in the memory.
You remember your seat.
Thus, you are a variable who remembers the address of another variable which is the seat.
In this case, you are a pointer because you have your seat location/address stored in your memory.
WHAT IS A POINTER?
A pointer is a variable which contains the address/location of another variable.
The declaration of a pointer is same as any other variable:
datatype *variable_name;
An asterisk (*) is used in the declaration of a pointer.
We will learn the significance of this shortly.
* and &
An asterisk (*) is read as the value at.
Thus, *a will be read as the value at a.
And, an ampersand (&) is read as the address of.
So, &a will be read as the address of a.
Thus, *a = &p;
This is read as: the value at a equals the address of p.
That is, a is a pointer containing the address of p.
Using pointers in C++
Consider the below snippet
int a = 5;
int *b = &a;
cout<<b;
Here we have a variable a containing value 5 and another variable which is a pointer containing the address of a, then we are printing variable b on the screen.
The output of the above snippet will be a hexadecimal value like the one shown below
0x7ffc439eefe4
Now,
int a = 5;
int *b = &a;
cout<<*b;
We have made a slight change, we are now printing value at b to the screen.
The output of the above snippet will be
5
And,
int a = 5;
cout<<&a;
Now we are printing address of a to the screen.
The output of the above snippet will be a hexadecimal value like the one shown below:
0x7fffb30670ac
In C++, there are many operations which can be carried out using pointers.
Addition, subtraction, swapping values of variables.
In short, we can carry out every operation with the help of pointers.
* and & stand for value at and address of respectively.
To summarize
- A pointer is a variable containing the address of another variable.
- An asterisk (*) is read as the value at.
- And, an ampersand (&) is read as the address of.
- The declaration of a pointer is same as any other variable except the asterisk which tells that it is a pointer.
- datatype *variable_name;