Tuesday 8 November 2011

Can math operations be performed on a void pointer? in C programming

Can math operations be performed on a void pointer?

No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. By
definition, if you have a void pointer, you don’t know what it’s pointing to, so you don’t know the size of
what it’s pointing to.
If you want pointer arithmetic to work on raw addresses, use character pointers.

NOTE
You can cast your void* to a char*, do the arithmetic, and cast it back to a void*.

Cross Reference:

VII.7: Can you subtract pointers from each other? Why would you?
VII.8: When you add a value to a pointer, what is really added?

No comments:

Post a Comment