C++ Pointer To Pointer (Double Pointer)
In C++ a Pointer is a variable that is used to store the memory address of other variables. It is a variable that points to a data type (like int or string) of the same type and is created with the * operator.
Syntax of a Pointer in C++:
data_type_of_pointer *name_of_variable = & normal_variable;
What is a Pointer to a Pointer or Double Pointer in C++?
Now, we already know that a pointer stores the memory address of other variables. So, when we define a pointer to a pointer, the first pointer is used to store the address of the variables, and the second pointer stores the address of the first pointer. For this very reason, this is known as a Double Pointer or Pointer to Pointer.
The below diagram explains the concept of Double Pointers :
The above diagram shows the memory representation of a Pointer to Pointer or a Double Pointer, we can easily understand that the address of the variable (i.e Address 1) is stored in Pointer 1 and the address of Pointer 1(i.e Address 2) is stored in Pointer 2. This is known as Double Pointers or Pointer to Pointer.
How to Declare a Pointer to a Pointer in C ++?
Declaring a Pointer to Pointer is similar to declaring a pointer in C++. The difference is we have to use an additional * operator before the name of a Pointer in C++.
Syntax of a Pointer to Pointer(Double Pointer) in C++:
data_type_of_pointer **name_of_variable = & normal_pointer_variable;
int val = 169;
int *ptr = &val; // storing address of val to pointer ptr.
int **double_ptr = &ptr; // pointer to a pointer declared which is pointing to an integer.
The below diagram explains the concept of Double Pointers:
The above diagram shows the memory representation of a pointer to a pointer. The first pointer ptr1 stores the address of the variable and the second pointer ptr2 stores the address of the first pointer.
Below is the C++ Program to implement Pointer to Pointer:
Value of variable :- 169 Value of variable using single pointer :- 169 Value of variable using double pointer :- 169
What will be the size of a pointer to a pointer in C++?
In the C++ programming language double pointer behave similarly to a normal pointer. So, the size of the variable of the double-pointer and the size of the normal pointer variable is always equal.
Below is a C++ program to check the size of a double pointer:
Size of normal Pointer: 8 Size of double Pointer: 8
Note: The output of the above code also depends on the type of machine which is being used. The size of a pointer is not fixed in the C++ programming language and it totally depends on other factors like CPU architecture and OS used. Usually, for a 64-bit Operating System, a size of 8 bytes memory and for a 32-bit Operating system, a size of 4 bytes memory is assigned.
Time complexity: O(1).
Auxiliary space: O(1).