Explain the concept of pointer to pointer and void pointer in C language?

CServer Side ProgrammingProgramming

Double pointer or pointer to pointer is a variable that holds the address of another pointer.

Following is the declaration for a pointer to a pointer −

datatype ** pointer_name;

For example, int **p; p is a pointer to pointer

Initialization − ‘&’ is used for initialization.

For example,

int a = 10;
int *p;
int **q;
p = &a;

Accessing − Indirection operator (*) is used for accessing.

Example

Following is the C program for the pointer to pointer −

 Live Demo

#include<stdio.h>
main ( ){
   int A = 10;
   int *p;
   int **q;
   p = &A;
   q = &p;
   printf("A =%d",A);
   printf("A value of pointer = %d", *p);
   printf("A value of double pointer = %d", **q);
}

Output

When the above program is executed, it produces the following result −

A=10
A value of pointer = 10
A value of double pointer = 10

Void pointers

It is a type of pointer that can hold the address of any datatype variable (or) can point to any datatype variable.

Following is the declaration for the void pointer −

void *pointername;

For example, void *vp;

Accessing − Type cast operator is for accessing the value of a variable through its pointer.

The syntax is as follows −

* ( (type cast) void pointer)

For example,

int i=10;
void *vp;
vp = &i;
printf ("%d", * ((int*) vp));
type cast

Example

Following is the C program for the void pointer −

#include<stdio.h>
main ( ){
   int i =10;
   float f = 5.34;
   void *vp;
   clrscr ( );
   vp = &i;
   printf ("i = %d", * ((int*)vp));
   vp = &f;
   printf ( "f = %f", * ((float*) vp));
   getch ( );
}

Output

When the above program is executed, it produces the following result −

i = 10
f = 5.34
raja
Published on 08-Mar-2021 06:40:29
Advertisements