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).
C library macro - offsetof() The C library macro offsetof(type, member-designator) results in a constant integer of type size_t which is the offset in bytes of a structure member from the beginning of the structure. The member is given by member-designator, and the name of the structure is given in type.
A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure. Syntax: struct name_1.
A structure inside another structure is called nested structure. Consider the following example, struct emp{ int eno; char ename[30]; float sal; float da; float hra; float ea; }e; All the items comes under allowances can be grouped together and declared under a sub – structure as shown below.
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 static
typet;
, &(t.
member-designator)
evaluates to an address constant. The member-designator doesn't have to be a simple identifier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With