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.
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.
Use void*
But keep in mind that standard prohibits pointer arithmetic for void*, and you cannot dereference void*, and there are other limitations for void*. So, you better always cast void* to some meaningful pointers to avoid problems.
Use char*
when you work with char type or
when you want to work with some type in byte-by-byte manner. Because of sizeof(char) is always 1 byte, char* pointer will change by one byte if you increment / decrement it (will point to next / previous byte in memory respectively).
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.
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,
© 2022 - 2025 — McMap. All rights reserved.
void
pointer when you want to hide a data structure inside a module and give the user "just a pointer" to interact with your module. – Thrasonicalconst
qualifier on something when you "can achieve the same functionality" without it by simply not assigning to it. But being able to convey the meaning (both to human readers and to the compiler) has value in itself. – Epineurium