Pointer:
A simple definition of a pointer can be a data type that stores the address of other data type.
Some of the operators that one must know before understanding the rule to declare pointers are:
A. Address of operator: Suppose we have a variable ‘a’ of integer datatype. So, to mention it’s address we can write ‘&a’.
i.e., &a indicates address of a.
B. Dereference operator: *
Basic syntax to declare a pointer:
data_type* name;
For example,
int* a;
char* p;
float* s;
(One thing is important to keep in mind is that ,we can’t store the address of integer data_type in a pointer having data_type other than integer, and the same rule goes for other data types as well.)
i.e., it is wrong to write :
int a = 5;
float* b = &a;
The data_type of pointer ‘b’ should also be integer only.
Let us try to explore the concept of pointers using an example mentioned below:
int a = 5;
int* p = &a;
Here, we have declared a variable ‘a’ of integer data_type and it is storing a value 5. Also in the next line we have declared a pointer ‘p’ and it is storing the address of ‘a’.
If we print the value of p, we will simply get the address of ‘a’ and if we print *p , we will get the value at the address, being stored by p(that is why * is called as “Dereference operator” or simply “value at”). Address of a variable can be any hexadecimal number or any garbage value ,which is evaluated by computer only and can vary from computer to computer.
Code Example:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
int a=5;
int* p=&a;
cout<<"a= "<<a<<endl;
cout<<"p= "<<p<<endl;
cout<<"*p= "<<*p<<endl;
return 0;
}
Output:
a= 5
p= 0x61ff08
*p= 5
The output value printed above (p= 0x61ff08) may vary on your code editor, as every system stores variables at different memory locations.
Pointer to pointer:
A pointer that stores the address of other pointer.
Example,
int a=5;
int* b= &a;
int** c= &b;
Here,
- ‘a’ is simply a variable of integer data_type, which is storing an integer 5.
- ‘b’ is a pointer which is storing the address of ‘a’. (*b will give 5 as output)
- ‘c’ is pointer to pointer which is storing the address of pointer ‘b’. (*c will give address of ‘a’ as output and **c will give 5 as output)
*b means value at &a i.e., 5, *c means value at address of b i.e., address of a.
Now, since *c means &a then **c will be value at &a i.e., 5.
Code Example:
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
int a=5;
int* b=&a;
int** c=&b;
cout<<a<<endl;
cout<<&a<<endl;
cout<<b<<endl;
cout<<&b<<endl;
cout<<*b<<endl;
cout<<c<<endl;
cout<<*c<<endl;
cout<<**c<<endl;
return 0;
}
Output:
5
0x61ff08
0x61ff08
0x61ff04
5
0x61ff04
0x61ff08
5
The output values printed above (something like, 0x61ff08) may vary on your code editor, as every system stores variables at different memory locations.
This article was exclusively written by Sadhana Sharma.
Read Next: Sieve of Eratosthenes