VOID POINTER: A void pointer is a pointer that has no associated data type with it. A void pointer can hold an address of any type and can be typecasted to any type.
Void Pointer performs the same task of storing the address of some variable, but the difference come in its data type association. It's a general purpose pointer, it can store the address of character datatype, float datatype, integer datatype, etc. No datatype is associated with it.
and we need to know what is typecasting,
TYPECASTING: A typecasting is basically a conversion from one type to another. There are two types of type conversion:
(1) Implicit Type Conversion: Done by the compiler on its own, without any external trigger from the user.
example:
(2) Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user can typecast the result to make it of a particular data type.
example: Explicit type conversion
#include<stdio.h>
int
main()
{
double
x = 1.2;
// Explicit conversion from double to int
int
sum = (
int
)x + 1;
printf
(
"sum = %d"
, sum);
return
0;
}
output: sum = 2
(src:geeksforgeeks)
Now the question is that why we need to typecast.
Let us take an example,
int a = 5;
int *p = &a;
printf("%d", *p); // it will simply print the data value stored in a and that it pointing by p.
Void Pointer perform the same task of storing the address of some variable, but the difference come in its data type association
int a = 5;
char c = 'x' ;
float f = 5.9;
void* p1 = &a; // no problem
void* p2 = &c; // no problem
void* p3 = &f; // no problem
printf("%d",*p1); // here compiler will confuse about data type and gives error: dereferencing 'void*' pointer invalid use of void expression
printf("%c",*p2); // here compiler will confuse about data type and gives error: dereferencing 'void*' pointer invalid use of void expression
printf("%f",*p3); // here compiler will confuse about data type and gives error: dereferencing 'void*' pointer invalid use of void expression
thats why we need to type cast void pointer.
and writing the above code in the following way gives no error.
printf("%d",*(int*)p1); // no error
printf("%c",*(char*)p2); // no error
printf("%f",*(float*)p3); // no error