This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

union/struct problem

Hello,

it works in devcpp (as c project) but not working in Keil. What is my fault.
output must be "12345" but it is not.

typedef union {
        u8      Reg8[5];
        struct
        {
                u8      Select;
                u32     Value32;
        }Regs;
}CreditLoadRegs_t;


const char  MyArray[]={"12345"};

void MyFonc(char *Buf)
{
    CreditLoadRegs_t *fPtr = (CreditLoadRegs_t *)Buf;
    printf("%s",fPtr->Reg8);
}

int main(void)
{
    MyFonc(MyArray);

    return 0;
}

Parents
  • The union is only about overlaying data - not packing data.

    And it isn't intended to overlay as a way to type-convert, but to allow conditional existence of data from a time when RAM was at a premium.

    Any and all type conversion performed using unions are a kind of abuse. When done correctly, it can in some limited cases be used in a "correct" way without undefined behavior. But it is a slippery slope - the language standard didn't intend you to write to one member of the union and read out the data using a different member of the union.

Reply
  • The union is only about overlaying data - not packing data.

    And it isn't intended to overlay as a way to type-convert, but to allow conditional existence of data from a time when RAM was at a premium.

    Any and all type conversion performed using unions are a kind of abuse. When done correctly, it can in some limited cases be used in a "correct" way without undefined behavior. But it is a slippery slope - the language standard didn't intend you to write to one member of the union and read out the data using a different member of the union.

Children