August
August

Reputation: 100

How to find index of a struct element as index of byte array in union (in standard C)

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

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726939

Since the initial byte of myStrunctand 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

Related Questions