Home > Mobile >  C structure reference from member reference
C structure reference from member reference

Time:05-06

Given the following setup...

struct A {unsigned char _data;};
struct B {unsigned char _data;};
struct C {A a; B b;};

// in this context (ar) is known to be the "a" of some C instance
A& ar = ...;
B& br = get_sister(ar); // the "b" of the same C instance that (ar) belongs to
C& cr = get_parent(ar); // the C instance that (ar) belongs to

...how do I get br and cr from ar without UB (undefined behaviour)?

CodePudding user response:

Only if you know for a fact that ar is referencing a C::a member, then you can use offsetof() (which should return 0 in this case, since a is the 1st non-static data member of C, but best not to assume that) to help you access the C object, eg:

C& get_parent(A& ar)
{
    return *reinterpret_cast<C*>(reinterpret_cast<char*>(&ar) - offsetof(C, a));
}

B& get_sister(A& ar)
{
    return get_parent(ar).b;
}

Online Demo

  • Related