Pointer to Pointer (Double Pointer)

A pointer to a pointer introduces an additional level of indirection. 

It is a pointer that holds the memory address of another pointer.

The declaration of a double pointer involves two asterisks (**), and it can be used to point to the address of a regular pointer.

int y = 20;

int *ptr1 = &y;    // ptr1 is a pointer to an integer, storing the address of y

int **ptr2 = &ptr1; // ptr2 is a pointer to a pointer, storing the address of ptr1

ptr1 is a regular pointer storing the address of the integer variable y.

ptr2 is a double pointer storing the address of ptr1.

Declaration and Initialization:

int x = 10;: Initializes an integer variable x with the value 10.

int *ptr1 = &x;: Declares a pointer to an integer ptr1 and initializes it with the address of x.

Pointer to Pointer (Double Pointer):

int **ptr2 = &ptr1;: Declares a double pointer ptr2 and initializes it with the address of ptr1. Now, ptr2 is pointing to the address of ptr1.

Printing Values and Addresses:

printf("Value of x: %d\n", x);: Prints the value of x.

printf("Address of x: %p\n", (void *)&x);: Prints the address of x.

printf("Value of ptr1 (address of x): %p\n", (void *)ptr1);: Prints the value of ptr1, which is the address of x.

printf("Value of ptr2 (address of ptr1): %p\n", (void *)ptr2);: Prints the value of ptr2, which is the address of ptr1.

Dereferencing Pointers:

printf("Value at the address stored in ptr1: %d\n", *ptr1);: Dereferences ptr1 to access the value at the address it points to (value of x).

printf("Value at the address stored in ptr2 (value of x): %d\n", **ptr2);: Dereferences ptr2 twice to access the value at the address it points to, which is the address of ptr1, and then dereferences ptr1 to access the value at the address it points to (value of x).

Post a Comment

0 Comments