Reputation: 330
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.
Upvotes: 6
Views: 2240
Reputation: 21
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).
Upvotes: 2
Reputation: 820
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,
Upvotes: -1
Reputation: 456
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.
Upvotes: 1
Reputation: 42119
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.
Upvotes: 10