Get pointer to object from pointer to some member

If you are sure that the pointer is really pointing to the member b in the structure, like if someone did

Thing t;
some_function(&t.b);

Then you should be able to use the offsetof macro to get a pointer to the structure:

std::size_t offset = offsetof(Thing, b);
Thing* thing = reinterpret_cast<Thing*>(reinterpret_cast<char*>(ptr) - offset);

Note that if the pointer ptr doesn’t actually point to the Thing::b member, then the above code will lead to undefined behavior if you use the pointer thing.

Leave a Comment