Pointers are a very important concepts in C++. With the use of pointers we can directly access the value at a memory of the machine that we are running and it will be of great use if we use it the right way. Pointers are used to “store the address of a variable which is of the pointer type”.
A pointer of type T can be declared as T* variable;which is a Pointer to T.
Concept of Pointers

In pointers the two main concepts are dereferencing (also called as indirection) which is referencing to the object pointed by the pointer. The other one is referencing, that is referencing the value at the address stored by the pointer. Pointers are a powerful concepts used in almost every libraries. Arrays in C++ are similar to pointers. The first element in the array points to the second elements address by the variable type.
Example
#include <iostream>
using namespace std;
int main() {
char ch = 'a';
// pointer to char
char* ch_ptr = &ch;
// pointer to pointer to char
char** ch_ptr_ptr = &ch_ptr;
cout<< "The address of character 'ch' is " << (int)&ch <<endl;
cout<< "The value at 'ch' is " << ch <<endl;
cout<< "The address of ch_ptr is " << (int)&ch_ptr <<endl;
cout<< "The value at 'ch_ptr' (i.e address of 'ch') is "<< (int)ch_ptr <<endl;
cout<< "The value pointed by the pointer is " << *ch_ptr <<endl;
cout<< "The address of ch_ptr_ptr is "<< (int)&ch_ptr_ptr <<endl;
cout<< "The value at 'ch_ptr_ptr' (i.e address of 'ch_ptr') is "<< (int)ch_ptr_ptr <<endl;
cout<< "The value pointed by the pointer is " << (int)*ch_ptr_ptr <<endl;
cout<< "The value pointed by ** is " << *(*ch_ptr_ptr) <<endl;
return 1;
}
In the above code i have declared three variables,
- A char variable
ch = 'a'
with a character literal assigned to it. - A pointer to char variable which is pointed to the address of the char variable using the dereferencing operator
ch_ptr = &ch
. The value atch_ptr
(i.e ‘a’ the value of ch) can be accessed using the referencing operator*ch_ptr
. - Finally a Pointer to Pointer variable which is used to hold the address of another pointer variable
ch_ptr_ptr = &ch_ptr
. The above concept is visually show below.
Memory Representation Of Pointers
The above diagram shows the memory representation of the pointer and how they point to each variables address. In ch_ptr variable stores the address location of ch and ch_ptr_ptr stores the address of ch_ptr. In the above program i have casted the 16-bit hexadecimal representation of the address to int so that it will be in a more understandable way. The output of the above program is shown below and with the output displayed you can understand the concepts of pointer.
