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.
eg
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).
Yes, you can still use offsetof
.
Eg
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 static
type t;
, &(t.
member-designator )
evaluates to an address constant. The member-designator doesn't have to be a simple identifier.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.