I know that we have different pointers like int
, float
, and char
. A void
pointer is the only pointer which can hold all o
Dead simple:
void* p;
*p; // compile error!
Or to put it in words; a void pointer can not be dereferenced.
Perhaps you should rename the question why do we have pointers, or rather don't and just search for that question on SO.
When You use pointer to float or int (for example) compiler knows how many bytes it should take from memory (sizeof(int) for int* for example).
With void You would have to tell each time to compiler how many bytes it have to take (by writing (int*)some_void_ptr for example.
But this is great simplification.
int o = 12;
void *i = &o;
How would you access the int that i
points to if there were only void pointers and no int*. You might know that on your platform an int is 4 bytes so you could memcpy 4 bytes from the start of whatever the void* points to into a temporary int and then use that. But that's not very convenient.
Or given a
struct Pair {
char *first;
char *second;
};
how useful would a void pointer to struct Pair be ? You'd likely want to access its first
member and that's a lot of work if you couldn't have a pointer to a struct Pair.
Type safety. Defining the type of pointers helps the compiler find errors where you are trying to use data of the wrong type through a pointer. That's the reason C has types in the first place.
Two Words: Type Safety
There's a little tidbit on type safety (or lack thereof) in C on Wikipedia that might shed some light for you.
Is there any other reason that pointers other than void are present in C language?
They are an awesome way to handle memory chunks freely. : )