Why you can't dereference a void* pointer

This tip submitted by ashish mathur on 2010-05-19 12:29:40. It has been viewed 24896 times.
Rating of 5.1 with 72 votes

The compiler will not let you dereference a void* pointer because it does not know the size of the object pointed to. If the pointer points to a char, which is one byte, the compiler needs to access only that one byte; if the pointer points to a double, not only is there more memory that needs to be accessed, but the layout is very different since it is represented as a floating point number.

You can of course use a void*, and it's very handy for writing generic code in C without templates, but you need to typecast your pointer to the right type before you dereference it.

More tips

Help your fellow programmers! Add a tip!