Pointer arithmetic for void pointer in C

Viewed 154513

When a pointer to a particular type (say int, char, float, ..) is incremented, its value is increased by the size of that data type. If a void pointer which points to data of size x is incremented, how does it get to point x bytes ahead? How does the compiler know to add x to value of the pointer?

9 Answers

Pointer arithmetic is not allowed in the void pointer.

Reason: Pointer arithmetic is not the same as normal arithmetic, as it happens relative to the base address.

Solution: Use the type cast operator at the time of the arithmetic, this will make the base data type known for the expression doing the pointer arithmetic. ex: point is the void pointer

*point=*point +1; //Not valid
*(int *)point= *(int *)point +1; //valid
Related