Every variable in C++ has an address which is a hexadecimal number (a hexadecimal number always starts with “0x”), we can see the address of any variable in C++ if we put an ampersand(&) symbol before it.
#include<bits/stdc++.h> // It is basically a header file that includes every standard library
using namespace std;
int main()
{
int var = 10;
cout<<"address is : "<<&var; // 0x61ff0c
return 0;
}
Pointers in c++/c is a variable that points to another variable i.e. a pointer stores the address of another variable.
int* p; // pointer declared and points to garbage value
This type of pointer declaration is not a very good practice as having pointers pointing to garbage values can be dangerous. It is always a good practice to give the address to your pointer while declaring it or else you can point it to NULL (all capital letters).
int var = 10;
int* ptr1 = &var; // stores address to variable var. (ptr1 points to var)
int* ptr2 = NULL; // points to NULL
Dereferencing pointers in c++
Pointers in c++ provide an alternative way to reach the value of the pointed variable.
int var = 10;
int* p = &var;
Now, we can access the value of the variable var
in 2 ways
1. We can directly use the variable var
to access its value (10 here)
2. We can deference the pointer to access the value of the variable var
. we can dereference the pointer by placing an asterisk(*) before the pointer.
example : *p
*p
prints 10 as p (pointer) points to var (variable)
Double pointer in c++
A double pointer in c++ is a variable that points to the address of another pointer.
#include<bits/stdc++.h> // It is basically a header file that includes every standard library
using namespace std;
int main()
{
int var = 10;
int* ptr1 = &var;
int** ptr2 = &ptr1;
cout<<"var : "<<var<<"\n";
cout<<"*ptr1 : "<<*ptr1<<"\n";
cout<<"**ptr2 : "<<**ptr2<<"\n";
return 0;
}
All the 3 cout
statements print 10. a double pointer is declared like int** ptr2 = &ptr1;
. The double-pointer needs 2 asterisks (**) and the triple pointer similarly needs 3 asterisks(***) and so on.
Remember a double-pointer can only store the address of a pointer and a triple pointer can only store the address of a double-pointer and so on.
To get a deep understanding of memory layout in C and C++ refer to this link.
Refer GeeksForGeeks for more information on pointers in c++.