I have a 255 byte array containing some data
- flag: 1 byte (unsigned char)
- address: 4 bytes (unsigned int)
- text: 13 bytes (char[13])
My union looks like this:
union {
unsigned char buf[255];
struct{
unsigned char flag;
unsigned int address;
char text[13];
} structure;
} the_union
I used the following code to treat a buffer of data as my union, and through the union I can access it using the struct. (buf was passed in as a function parameter)
the_union * ptr = (the_union*) buf;
char flag = ptr->structure.flag;
unsigned int address = ptr->structure.address;
char * text = (char*) ptr->structure.text;
While debugging, I noticed that while the values I got in the buffer matched the structure I was expecting, when I tried to access them in the union, it was incorrect.
In my buffer, I had the following bytes:
[0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x00, 0x00, .... ]
The values I got from my structure though were the following:
- flag = 0x00
- address = 0x00010203
- text = { 0x04, 0x05, 0x00, 0x00, ... }
I was expecting flag to be 0, address to be 0, and text to be {0x01, 0x02, 0x03, 0x04, 0x05, 0x00, 0x00, ...}. It seems that the alignment is wrong during access.
What is the explanation for this?