In this tutorial, you are going to learn about Void Pointers in C. What is a void pointer, use of void pointers and use of void pointers in malloc and calloc function.
Void Pointers in C
Void Pointer is a pointer which has no associated data type with it. It can point to any data of any data type and can be typecasted to any type.
Example:
int main()
{
int n=20;
void *ptr= &n;
printf("%d", *(int*)ptr);
return 0;
}
OUTPUT: 20
We cannot dereference a void pointer directly, so it is important for us to typecast our pointer before dereferencing it. If you are using it directly, you will get an error message.
Use of Void Pointer
malloc and calloc are built-in functions which are used to allocated memory dynamically. These two functions returns a void pointer and due to this reason, they can allocate a memory for any type of data.
Syntax: void* malloc(size_t size);
malloc and calloc are used to allocate memory at runtime.
This article on Void Pointers in C is contributed by Rajnish Kumar. If you like TheCode11, then do follow us on Facebook, Twitter and Instagram.