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.
We use the void pointers to overcome the issue of assigning separate values to different data types in a program. The pointer to void can be used in generic functions in C because it is capable of pointing to any data type.
void* to char**You can't. You need reinterpret_cast. You have a 'pointer to anything' and have decided to treat it as a 'pointer to a char*'. That is 'reinterpreting' the type of the memory without applying any conversions.
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type. // typecasted to any type like int *, char *, ..
But in the case of a void pointer we need to typecast the pointer variable to dereference it. This is because a void pointer has no data type associated with it. There is no way the compiler can know (or guess?) what type of data is pointed to by the void pointer.
Most pointer conversions to and from (void *) can be done without a cast but the use of (char *) is a reminiscence of the old times. GCC does not warn about pointer arithmetic on (void *) as it is not a compiler intended to be compliant with standard C but for GNU C.
The C++ idiom is to use templates, and the standard library provides a good many useful ones (including a linked list). Using void* instead of char* provides a certain measure of type safety. You are telling the compiler "I should never be allowed to dereference one of these pointers."
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With