C Control StatementsC FunctionsC ArrayC PointerC Dynamic MemoryC StringC MathC StructureC UnionC File HandlingC PreprocessorC Command LineC Misc |
Void pointer in cso in the previous session of pointer we understand that a pointer should be assigned an address of the same type. for example if we have int type pointer, Then we can not store the address of float variable to this int type pointer. It is incorrect. These types mixed conversion can be perform using the explicitly casts but here it lead to undefined behaviour. there is exception to this rule is a pointer to void. A pointer to void is the generic pointer that can point to any data type. so we can stored or assign the address of any data type to void pointer. The syntax of declaration of void pointer
Declaration of the void pointer is given below:
In this example void is a keyword and ptr is variable declared as pointer of void type. let us take examples to understand
Note A void pointer can not be dereferenced simply by follow or using indirectional operator. before use dereferencing it should be type cast to an appropriate pointer data type. for example if we have vp is void pointer as in the above example, and it hold the address of integer data type variable (integer variable), Then we can not dereference it by writing *vp, we will have to writev*(int *)vp, here left most asterisk is indirection operator and (int *) is use for typecasting.
Size of the void pointer in C The size of the void pointer in C language equals to the pointer of character type and the representation of a pointer to void is the same as the pointer of character type. And The size of the pointer will will depending on the platform that you are using Let’s Take the example:
Advantages of void pointer 1. The calloc() and malloc() function return the void pointer, so these functions can be used to allocate the memory of any data type because void support all type. 2. And the void pointer in C langauge can also be used to implement the generic functions |