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

Question about structs and unions

Hello there,

I've faced a problem that I couldn't solve. I hope you people can help me.
I want to memcpy to a struct the datum in an array.

I've done it before, and it goes like this:

memcpy((void*)(&(frame.payload),(void*)array,frameSize);

frame is a struct like this:

typedef struct tag_FRAME{
  U8    frameSize;
  CMD   payload;
}FRAME;

and this is CMD (the payload, struct to where I want the datum to be):

typedef struct tag_CMD{
  U8    id;
  union{
        CMD1    cmd1;
        CMD2    cmd2;
        CMD3    cmd3;
        CMD4    cmd4;
        CMD5    cmd5;
        CMD6    cmd6;
  }Command;
}CMD;

And CMD1 is a struct with one member, an array of chars called arrayX[4].
Let's say buffer is {0x01 , 0x00 , 0x01 , 0x02 , 0x03}
The result I get is:
id = 0x01 (Correct)
arrayX[0] = 0x05; (the size, first member of the FRAME struct)
arrayX[1] = 0x01; (first member of the CMD struct)
arrayX[2] = 0x00; (this should be the value in arrayX[0])
arrayX[3] = 0x01; (this should be the value in arrayX[1])

When debugging the address in the watch1, of the Command union inside the payload is the same address of the FRAME struct that contains the payload. If I put the id of the CMD struct to the end of it (after the union), and the frameSize of the FRAME struct to the end of it (after the CMD struct) it all works ok, the buffer is copyed correctly to the struct.

In other words, if the "normal" variables come after the structs and unions it all works as it should.

So, do anybody knows what's going on here?

Parents Reply Children
No data