Concept of void pointer

Pointer of type (int*) can hold address of type (int) only, (char*) can hold address of type (char) only , (float*) can hold address of type (float) only ....

We cannot assign address of integer variable to pointer of character type .
i.e consider  following statements

float *fptr;
int   a=10;
.....
fptr=&a;    /* This line shows compile time error*/

We can use void pointer as an exception to above.
Void pointer is an general purpose pointer type used to hold address of variable of any type.
Syntax:
 void *vptr; 
NOTE:- Void pointer cannot be directly dereferenced like other pointers. Before dereferencing we need to typecast our void pointer to required data type.

e.g

#include <stdio.h>
void main()
{
  int a=10;
  float b=12.12;
  void *vptr;

   vptr=&a;
   printf("%d", *((int*)vptr));

   vptr=&b;
   printf("%f", *((float*)vptr));
 
}


download above source code from  here

Share this post and spread the knowledge --->

No comments:

Post a Comment