4

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?

3
  • 4
    Arithmetic on void* is not just prohibited, but meaningless. There is no sizeof(void). Commented Feb 20, 2011 at 19:34
  • Interestingly(?), gcc allows arithmetic operations on void*, while g++ seems not to allow it. Commented Feb 20, 2011 at 22:55
  • @IseWisteria: As of version 4.7.2, g++ permits it (with a warning) if you specify -fpermissive. Commented Jul 18, 2014 at 21:41

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

7 Comments

You might have a valid reason for doing this for interop across a language boundary.
+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. :)
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.
@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++.
@MatějZábský: That is rather condescending of you.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.