A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type. A void pointer is a generic pointer. It can store the address of any type of object and it can be type-casted to any types. According to C standard, the pointer to void shall have the same representation and alignment requirements as a pointer to a character type.A void pointer declaration is similar to the normal pointer, but the difference is that instead of data types we use the void keyword.
Facts about void pointers:
- malloc() and calloc() return void * type and this allows these functions to be used to allocate memory of any data type (just because of void *)
// Note that malloc() returns void * which can be typecasted to any type like int *, char *, ..
int *x = malloc(sizeof(int) * n);
- void pointers cannot be dereferenced.
int a = 10;
void *ptr = &a;
Let’s take an example:
int a = 100, *ip;
float f = 12.2, *fp;
char ch = ‘a’;
vp = &a; // ok
vp = ip; // ok
vp = fp; // ok
ip = &f; // wrong since type of ip is pointer to int
fp = ip; // wrong since type of fp is pointer to float
Dereferencing a void Pointer
We can’t just dereference a void pointer using indirection (*) operator. For example:
int a = 100;
vp = &a;
printf("%d", *vp); // wrong
Before you dereference a void pointer it must be typecasted to appropriate pointer type. For example: In the above snippet void pointer vp is pointing to the address of integer variable a. So in this case vp is acting as a pointer to int or (int *). Hence the proper typecast in this case is (int*).
Now the type of vptr temporarily changes from void pointer to pointer to int or (int*) , and we already know how to dereference a pointer to int, just precede it with indirection operator (*)
typecasting changes type of vp temporarily until the evaluation of the expression, everywhere else in the program vp is still a void pointer.