Being new to C, the only practical usage I have gotten out of void pointers is for versatile functions that may store different data types in a given pointer. Therefore I did not type-cast my pointer when doing memory allocation.
I have seen some code examples that sometimes use void pointers, but they get type-cast. Why is this useful? Why not directly create desired type of pointer instead of a void?
A void pointer is a pointer that can point to any type of object, but does not know what type of object it points to. A void pointer must be explicitly cast into another type of pointer to perform indirection. A null pointer is a pointer that does not point to an address.
The void pointer in C is a pointer that is not associated with any data types. It points to some data location in the storage. This means that it points to the address of variables. It is also called the general purpose pointer.
Why we use void pointers? We use void pointers because of its reusability. Void pointers can store the object of any type, and we can retrieve the object of any type by using the indirection operator with proper typecasting.
An open (void) pointer can hold a pointer of any type. Casting an open pointer to other pointer types and casting other pointer types to an open pointer does not result in a compile time error. Note: You might receive a runtime exception if the pointer contains a value unsuitable for the context.
There are two reasons for casting a void pointer to another type in C.
*(int*)p = 42
)The reason for 1 should be obvious. Number two is because C++ disallows the implicit conversion from void*
to other types, while C allows it.
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