I was working with some (of what I thought was) bad code that had a union like:
union my_msg_union
{
struct message5;
char buffer[256]
} message;
The buffer was filled with 256 bytes from comms. The struct is something like:
struct message5 {
uint8 id;
uint16 size;
uint32 data;
uint8 num_ids;
uint16 ids[4];
} message5d
The same code was being compiled on heaps of architectures (8bit AVR, 16bit phillips, 32bit arm, 32bit x86 and amd64).
The problem I thought was the use of the union: The code just a blob of serial recieved bytes into the buffer, then reads the values out through the struct, without considering alignment/padding of the struct.
Sure enough, a quick look at sizeof(message5d) on different systems gave different results.
What surprised me however is that whenever the union with the char [] existed, all instances of all structs of that type, on all systems, dropped their padding/alignment, and made sure to be sequential bytes.
Is this a C standard or just something that compiler authors have put in to 'help'?