Advantages of void pointer in C Language
Categories: C language
1. The malloc() and calloc() function return the void pointer, so these functions can be used to allocate the memory of any data type.
2. The void pointer in C can also be used to implement the generic functions in C.
Some important points related to void pointer are:
1. Dereferencing a void pointer in C
2. The void pointer in C cannot be dereferenced directly. Let's see the below example.
In the above code, *ptr is a void pointer which is pointing to the integer variable 'a'. As we already know that the void pointer cannot be dereferenced, so the above code will give the compile-time error because we are printing the value of the variable pointed by the pointer 'ptr' directly.
Now, we rewrite the above code to remove the error.
#include <stdio.h>
int main()
{
int a=90;
void *ptr;
ptr=&a;
printf("Value which is pointed by ptr pointer : %d",*(int*)ptr);
return 0;
}
In the above code, we typecast the void pointer to the integer pointer by using the statement given below:
(int*)ptr;
Then, we print the value of the variable which is pointed by the void pointer 'ptr' by using the statement given below:
*(int*)ptr;