In which situation should we prefer a void pointer over a char pointer or vice-versa?
As a matter of fact both can be type cast to any of the data types.
A void
pointer is a pointer to "any type", and it needs to be converted to a pointer to an actual type before it may be dereferenced.
A pointer to char
is a pointer to char
, that happens to have the property that you could also access (parts of) other types through it.
You should use void *
when the meaning is intended to be "any type" (or one of several types, etc). You should use char *
when you access either a char
(obviously), or the individual bytes of another type as raw bytes.