chbaker0
chbaker0

Reputation: 1788

Can I legally cast a pointer to a struct member to a pointer to the struct?

Consider a struct like so, for example:

struct Foo
{
    int a, b;
};

If I have a pointer ptr to an int that I know points to b in a Foo struct, is it legal to do this?

Foo *foo = reinterpret_cast<Foo*>(reinterpret_cast<char*>(ptr) - offsetof(Foo, b));

If so, is this legal for any struct? If not, is there any legal way to accomplish the same effect?

Upvotes: 1

Views: 182

Answers (1)

R Sahu
R Sahu

Reputation: 206577

From http://en.cppreference.com/w/cpp/types/offsetof:

The macro offsetof expands to a constant of type std::size_t, the value of which is the offset, in bytes, from the beginning of an object of specified type to its specified member, including padding if any.

If type is not a standard layout type, the behavior is undefined.

This make uses of offsetof subject to undefined behavior for classes and structs that are not standard layout type.

For classes and structs that are standard layout type, I don't see any potential problems.

Upvotes: 2

Related Questions