Generally a pointer variable is declared using data type. Where Data type indicates type of variable whose address can be stored in the pointer variable.
ptr=&a; // Valid
ptr=&b; // Not Valid
Here, pointer is declared as integer. So it can be assigned an address of integer variable. If you are trying to assign an address of float variable then it will generate compile error.
Thus a pointer variable declared using a particular data type can not hold the address of variables of other data types. This problem can be solved using concept of Void Pointer.
Void Pointer is a general purpose pointer which can be used to store address of any variable of any data type (char, int, float etc.) to a void pointer variable.
General syntax for declaring void pointer is given below:
ptr = &a; // Valid
ptr=&b; // Valid
Dereferencing Void Pointer
The indirection operator * is known as dereferencing operator.
It is used to retrieve the value of the variable whose address is stored in the pointer.
In case of void pointer we need to type cast the pointer variable to dereference it. Thus in order to retrieve the value of the variable whose address is stored in void pointer we have to perform type casting.
int a = 5;
float b = 5.5;
ptr = &a; //Assign address of integer variable to void pointer.
printf (“Value of Integer Variable is %d”, *( (int *) ptr));
ptr = &b; // Assign address of float variable to void pointer
printf (“Value of Float variable is %f”, *( (float *) ptr));