void Pointers in C
A pointer to void, or void pointer for short, is a pointer with the type void *. As there are no objects with the type void, the type void * is used as the all-purpose pointer type. In other words, a void pointer can represent the address of any object but not its type. To access an object in memory, you must always convert a void pointer into an appropriate object pointer.
To declare a function that can be called with different types of pointer arguments, you can declare the appropriate parameters as pointers to void. When you call such a function, the compiler implicitly converts an object pointer argument into a void pointer. Consider the following example.
Example
#include <stdio.h> int main() { void *p; // declaring a void pointer int ab = 40; p = &ab; // assigning address of integer (ab) pointer to void pointer float f = 4.063; char *char1 = "hello"; printf("value of integer void pointer %d", *((int*) p)); p = &f; // assigning address of float (f) pointer to void pointer p printf("\nValue of float void pointer %f", *((float*) p)); p = char1; // assigning char pointer char1 to void pointer p printf("\nValue of char void pointer %s", ((char*) p)); return 0; }
Output
value of integer void pointer 40 Value of float void pointer 4.063000 Value of char void pointer hello