Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding relative offset in nested structure

Tags:

c

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).

like image 939
skyel Avatar asked Jun 03 '12 21:06

skyel


People also ask

How do you find the offset of a structure member?

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.

What is nested structure syntax?

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.

What is nested structure give example?

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.


1 Answers

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.

like image 64
CB Bailey Avatar answered Sep 23 '22 10:09

CB Bailey