问题
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.
回答1:
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.
回答2:
void pointers are used when the type of the variable the pointer would refer to is unknown. For example the malloc() function returns a void pointer referencing to the allocated memory. You could then cast the pointer to other data types.
There might be instances when you need to create a pointer to just store the address. You could use a void pointer there.
回答3:
Its more about code readability and structure, I dont wanna see a function need input for lets say pointer to struct and get it via char* , the first thing that comes to my mind if I see char* is a string(in pure c term, array of chars, null terminated), on the other hand with void* I am warned that something general is going to be passed, a good example is qsort
function.
so its not all about wether it works or compiles, it should be readable too,
来源:https://stackoverflow.com/questions/53932143/when-to-use-a-void-pointer-over-a-char-pointer