Pointer to pointers (C++)

The pointer to a pointer is a form of multiple of indirections or a class of pointers. In the case of a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the variable that contain the values desired.

Multiple indirections can be carried on to whatever extent desire, but there are a few cases where more pointer to a pointer is needed or written.

Excess indirection is  difficult to follow and process as it leads to conceptual errors. A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional * in front of the variable name. For example, this declaration informs the compiler that the next is a pointer to a pointer of type.

int **ptr2;

where ptr2 is a pointer which holds the address of the another pointer.

Example: The following program declares the pointer to pointer variable and displays the contents of these pointers.

//pointer to pointer
#include <iostream.h>
void main(void)
{
int value;
int *ptr1;
int *ptr2;
value=120;
cout << "value" << value << endl;
ptr1 = &value;
ptr2 = &ptr1;
cout << "pointer 1 = " << *ptr1 << endl;
cout << "pointer 2 = " << **ptr2 << endl;
}

Output of the above program:

value 120
pointer 1 = 120
pointer 2 = 120

It's very calm over here, why not leave a comment?

Leave a Reply

You must be logged in to post a comment.