Can void pointer hold any datatype?

Void pointer is a generic pointer.it has void at its datatype. It is a special type of pointer which can hold any type of data. While dereferencing through void pointer typecasting is must. We have studied that the address assigned to a pointer should be of the same type as specified in the pointer declaration.

Don’t know what are void pointers? Read in details: Void pointer in C

For example, if we declare the int pointer, then this int pointer cannot point to the float variable or some other type of variable i.e. it can point to only int type variable. To overcome this problem, we use a pointer to void.

#include<stdio.h>
int main() {
	int x=10;
	char ch="A";
	void *gp;                  // it is a generic pointer
	gp=&x;                    // address of int variable x is stored in gp
	printf("%d",*(int*)gp);    // explicit typecasting it convert gp to integer pointer
	gp=&ch;                   // address of char variable ch is stored in gp
	printf("%c",*(char*)gp);
	return 0;
}

Here, the void pointer is holding both the integer and char data type simultaneously, similarly it is able to hold any datatype.


You Missed

Also Checkout