Double pointer

Pointer is a variable that is used to store the address of other variables of a similar datatype. In the C programming language, there is a provision to store the address of the pointer variable in another variable. This variable is known as a pointer to a pointer variable and is also known as a double pointer.

Please refer to the pointer in C and its initialization before reading this article.

Syntax:

datatype **pointerName;

Example:

#include <stdio.h>

int main ()
{
   int var = 10;
   int *ptr = &var;
   
   int **double_ptr = &ptr;
   
   printf ("\n The address of the variable var is: %p\n", &var);
   printf ("\n The address stored by ptr is: %p\n", ptr);
   printf ("\n The address of ptr itself is: %p\n", &ptr);
   printf ("\n The value stored by ptr is: %d\n", *ptr);
   
   printf ("\n The address stored by double_ptr is: %p\n", double_ptr);
   printf ("\n The value stored by double_ptr is: %d\n", **double_ptr);
   return 0;
}

Output:

 The address of the variable var is: 0x7ffdf5da6e4c

 The address stored by ptr is: 0x7ffdf5da6e4c
 The address of ptr itself is: 0x7ffdf5da6e50

 The value stored by ptr is: 10

 The address stored by double_ptr is: 0x7ffdf5da6e50

 The value stored by double_ptr is: 10

Pictorial Representation:

  • Pointer variable “ptr” stores the address of the variable “var” which is “x”.
  • *ptr gives us the value stored at the address “x”.
  • Similarly, now the pointer to pointer variable “double_ptr” stores the address of pointer variable “ptr” and the value at the address of “ptr” is the address of variable “var”. Thus *ptr prints the address of “var”.
  • Thus *double_ptr means the address of variable “var”. Hence, the value at the address *double_ptr is 10. Thus **double_ptr prints 10.

Note:

  • To store the address of a normal variable, a single pointer is used.
  • To store the address of the pointer variable, a double pointer is used.
  • To store the address of a double pointer, a triple pointer is used, and so on.

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: