skyel
skyel

Reputation: 763

Finding relative offset in nested structure

So, offsetof(struct, field) returns the relative offset of field inside a plain structure. But is there a way to get the relative offset of a field inside of a nested structure.

e.g.

struct my_struct {
   int a;
   struct {
      int b;
      int c;
   } anonymous_struct;
}

Is there any way to get the offset of b and c relative to my_struct (at runtime).

Upvotes: 13

Views: 4068

Answers (1)

CB Bailey
CB Bailey

Reputation: 791849

Yes, you can still use offsetof.

E.g.

size_t boff = offsetof(struct my_struct, anonymous_struct.b);

The requirements of offsetof are that the type and member-designator must be such that given statictypet;, &(t.member-designator) evaluates to an address constant. The member-designator doesn't have to be a simple identifier.

Upvotes: 20

Related Questions