Double Pointer in C

Double Pointer in C

Double Pointer in C is defined as a pointer to store the address of another pointer. The first pointer is used to store the address of a variable And the second pointer is used to store the address of the first pointer. 

 

Diagramatic Representation

Double Pointer in C

For example

Double Pointer in C

 pr2 is a pointer is holds the address of an integer variable num. and there is another pointer pr1 that holds the address of another pointer pr2, the pointer pr1 here is a double-pointer.

 

Following is the syntax of declaring a double pointer is 

int **ptr; // pointer to a pointer which is pointing to an integer.

Here ptr is a double-pointer. There must be two *’s in the declaration of double pointer

 

Program

#include <stdio.h>
  
// C program to demonstrate pointer to pointer
int main()
{
    int var = 123;
  
    int *ptr2;
  
    
    int **ptr1;
  
    
    ptr2 = &var;
      
    ptr1 = &ptr2;
      
   
    printf("Value of var = %d\n", var );
    printf("Value of var using single pointer = %d\n", *ptr2 );
    printf("Value of var using double pointer = %d\n", **ptr1);
    
  return 0;
}

Output

Value of var = 123
Value of var using single pointer = 123
Value of var using double pointer = 123

Uses of Pointer-to-Pointer (Double Pointer)

  • We can use Pointers to pointers as “handles” to memory where you want to pass around a “handle” between functions to move to a new location memory.
  • Double Pointer or pointer to pointer is used as that if you want to have a list of characters (a word), use char *word for a list of words (a sentence), use char **sentence, and for list of sentences (a paragraph), use char ***paragraph.
  • When we want to protect the memory allocation or an assignment even outside of a function call then we use a pointer to the pointer.
  • You will need a double-pointer when to allocate space for a matrix or multi-dimensional arrays dynamically

 

Relate Post:

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *