I need to access an object in a buffer, pointed by a void pointer. The object is located at a certain offset but since arithmetic on a void pointer is prohibited how can I access the object?
1 Answer
You can cast the pointer to char* (+1 on such pointer is offset by one byte) or any other pointer type if that suits your needs better.
However, this approach is grossly error prone! You better check your design, something smells here! void* are in 99% of cases unnecessary in C++, designs that use them are usually more "C" than "C++". Remember, templates and inheritance should be the way to do these things.
7 Comments
David Heffernan
You might have a valid reason for doing this for interop across a language boundary.
Lightness Races in Orbit
+1 Absolutely correct. This is a complete hack and smells of a very poor design. Alternatively, of the misfortune of having to deal with C APIs. :)
BatchyX
sorry, but i don't see your point. You cannot escape using void* pointers when doing binary IO. Even boost's memory map api returns a void* pointer. avoiding void* is a good thing only when you can.
Matěj Zábský
@BatchyX Yes, there are specific cases where using void* can't be avoided - which is why I wrote only 99%, but I think it is much more likely that OP is just abusing void* to get around the strongly typed nature of C++.
TonyK
@MatějZábský: That is rather condescending of you.
|
void*is not just prohibited, but meaningless. There is nosizeof(void).-fpermissive.