samedi 2 mars 2019

Accessing unions in struct

Consider following code:

struct test1str
{
    int testintstr : 2;
    int testintstr2 : 1;
};

struct test2str
{
    int testintstr : 2;
    int testintstr2 : 1;
};

union test1uni
{
    int testint1;
    test1str str1;
};

union test2uni
{
    int testint2;
    test2str str2;
};

struct finalstruct
{
    test1uni union1;
    test2uni union2;
} finstr;

int* ptr = &finstr.union1.testint1;

finstr.union1.testint1 = 2;
finstr.union2.testint2 = 4;

cout << &finstr.union1 << endl;
cout << &finstr.union2 << endl;
printf("val: %i addr: %x\n", *ptr, ptr);
ptr++;
printf("val: %i addr: %x\n", *ptr, ptr);

Is there more appropriate way of accessing values from unions inside example finalstruct? Using code from above example, I could iterate throught all unions inside "finalstruct", and get int that was needed, but is there some other way to do this?

Assume that data size from all structs will be less or equal to the size of variable inside union - structs will be treated as bitfields, and data will be read through union variable.

Aucun commentaire:

Enregistrer un commentaire