Reputation: 100
I define a struct and an union as below:
struct MY_STRUCT
{
int a;
unsigned int x;
char c;
};
union MY_UNION
{
unsigned char myByte[sizeof(struct MY_STRUCT)];
struct MY_STRUCT myStruct;
};
How i find location (index) of myStruct.x
in myByte[]
array dynamically?
Upvotes: 2
Views: 917
Reputation: 726939
Since the initial byte of myStrunct
and myByte
have the same address, you can use offsetof
operator for that:
size_t offset = offsetof(MY_STRUCT, x);
MY_UNION u;
unsigned char *ptr = &u.myByte[offset];
Note that this is not done dynamically: offsetof
is computed statically at compile time.
Upvotes: 2