Concept of void pointer in C programming

Is it possible to dereference the void pointer without type-casting in C programming language…

No, void indicates the absence of type, it is not something you can dereference or assign to.

is there is any way of generalizing a function which can receive pointer and store it in void pointer and by using that void pointer we can make a generalized function..

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 from void*:

/* may receive wrong value if ptr is not 2-byte aligned */
uint16_t value = *(uint16_t*)ptr;
/* portable way of reading a little-endian value */
uint16_t value = *(uint8_t*)ptr
                | ((*((uint8_t*)ptr+1))<<8);

Also, is pointer arithmetic with void pointers possible…

Pointer arithmetic is not possible on pointers of void due to lack of concrete value underneath the pointer and hence the size.

void* p = ...
void *p2 = p + 1; /* what exactly is the size of void?? */

Leave a Comment