2

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;
2
  • That question seems to be C++ related, you do not seem to have problsm with C. Note that these are different languages. Commented Oct 7, 2015 at 23:45
  • But either langauge you should use proper (de)serialisation instead of casting. There are far too many problems with that. Commented Oct 7, 2015 at 23:58

1 Answer 1

3

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;
Sign up to request clarification or add additional context in comments.

3 Comments

I've never seen that syntax wizardy before (de-referencing a pointer typecast?!) but it worked great! Thanks!!
It casts address of array to address of struct, and then dereferences it. But please be aware that if we made it compile does not mean that the behavior is guaranteed. In this case it is vice versa.
This is the C answer. For C++ the more explicit way of doing it, which does exactly the same thing, is a *reinterpret_cast<sMYSTRUCT*>(byteArray); In most cases these two are equivalent but there are edge cases where a C-style cast might not do what you expect. Note that this is also undefined behavior. For a basic explanation of what the problem with this kind of type punning is and which kind of alternatives exist you might want to watch youtube.com/watch?v=_qzMpk-22cc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.