I'm a bit confused with a void* pointer in C. Especially after reading this question: Is the sizeof(some pointer) always equal to four?, where one person says there is no guarantee that sizeof(int *) == sizeof(double *)
My question is: is there a guarantee of sizeof(void*) >= sizeof(any other pointer type)? In other words, can I always assign a some_type* pointer to a void* pointer and then get it back as some_type*?
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. In C, malloc() and calloc() functions return void * or generic pointers.
The size of a void pointer is different in different systems. In 16-bit systems, the size of a void pointer is 2 bytes. In a 32-bit system, the size of a void pointer is 4 bytes. And, in a 64-bit system, the size of a void pointer is 8 bytes.
When you do pointer arithmetic adding or removing one unit means adding or removing the object pointed to size. Thus defining sizeof(void) as 1 helps defining void* as a pointer to byte (untyped memory address).
yes it is safe. Show activity on this post. In one case, malloc and free match, and in the other the allocated memory is returned. There are also secondary resources, and the constructor and destructor match.
Only data pointers. void *
can hold any data pointer, but not function pointers.
Here is a C FAQ.
void *'s are only guaranteed to hold object (i.e. data) pointers; it is not portable to convert a function pointer to type void *. (On some machines, function addresses can be very large, bigger than any data pointers.)
As for the first part, yes, different types can have pointers of different sizes:
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