ben
ben

Reputation: 481

Typecast char array into a structure (not a class/object)

Using only ANSI-C, I was hoping to copy a byte array into a struct,

alt_u8 byteArray[16];
sMYSTRUCT myVar;
myVar = (sMYSTRUCT)(byteArray);

but seems like I need C++ for this.. however when I enable c++, I get the error "no matching function for call to 'sMYSTRUCT::sMYSTRUCT(alt_u8 [16])"

I assume this is because the compiler doesn't know how to copy the data into the structure.. Is this correct? Is the only way to do this is define a class, create an object of that class, and THEN typecast the byte array?

    typedef struct
    {
        alt_u8 Byte0;
        alt_u8 Byte1;
    } stByte_1_0;

    typedef struct
    {
        union
        {
            alt_u16     WORD0;
            stByte_1_0  BYTE_1_0;
        } uSel;
    } stWord0;

    typedef struct
    {
        stByte_1_0  WORD0;
        alt_u16 WORD1;
    } sMYSTRUCT;

Upvotes: 2

Views: 225

Answers (1)

AlexD
AlexD

Reputation: 32566

Such casting is undefined behavior. I would strongly suggest to avoid it.

Nevertheless, if casting is really really needed and you are sure it is safe, try

myVar = *(sMYSTRUCT*)byteArray;

Upvotes: 3

Related Questions