Is it possible to dereference a void pointer without type-casting in the C programming language?
Also, is there any way of generalizing a function which can receive a pointer and store it in a void pointer and by using that void pointer, can we make a generalized function?
for e.g.:
void abc(void *a, int b)
{
if(b==1)
printf("%d",*(int*)a); // If integer pointer is received
else if(b==2)
printf("%c",*(char*)a); // If character pointer is received
else if(b==3)
printf("%f",*(float*)a); // If float pointer is received
}
I want to make this function generic without using if-else statements – is this possible?
Also if there are good internet articles which explain the concept of a void pointer, then it would be beneficial if you could provide the URLs.
Also, is pointer arithmetic with void pointers possible?
Best Answer
No,
void
indicates the absence of type, it is not something you can dereference or assign to.You cannot just dereference it in a portable way, as it may not be properly aligned. It may be an issue on some architectures like ARM, where pointer to a data type must be aligned at boundary of the size of data type (e.g. pointer to 32-bit integer must be aligned at 4-byte boundary to be dereferenced).
For example, reading
uint16_t
fromvoid*
:Pointer arithmetic is not possible on pointers of
void
due to lack of concrete value underneath the pointer and hence the size.