Dear all,
I have this ultra simple strcture
typedef struct { uint8_t Hora; uint16_t Data1; } EEpromPaqueteDatosS;
When I do sizeof(EEpromPaqueteDatosS) it returns 4!!! But if I do the sizeof of the same structure with only one variable, in other words, with uint8_t variable it returns 1 and with uint16_t it returns 2.. but if the structure have the two variables it returns 4!!
Also if I copy the structure to a uint8_t vector I can found a strange byte in the middle.. like this:
EEpromPaqueteDatosS EEpromPaqueteDatos; uint8 data[4];
EEpromPaqueteDatos.Hora = 0x10; EEpromPaqueteDatos.Data1= 0x1020;
When I copy the structure to data, data is like 0x10, 0x??, 0x20, 0x10.. why this extra byte!!!!
Can anybody help me with this???
Thanks
Yes - the normal solution is to let the compiler do what the compiler does.
It's common that data types larger than one byte have a requirement on alignment. So two-byte integers must often be stored on even addresses.
And the compiler must then also make sure that the full struct gets the same align as that internal element. So it doesn't matter if you have 16-bit + 8-bit fields - the compiler still needs to make the struct have same align as the 16-bit field. Hence if processor requires align for 16-bit field, then the full struct must have a size that is 2*n so that you can have an array of structs and each and every struct will start on a 2*n address.
Most compilers have some option to pack structs, but that is costly. If the processor do need 16-bit align for a 16-bit number than a packed structure requires the compiler to produce code that picks up the field as two 8-bit reads and then combines them. Ugly and costly.
So you normally do not want to play with packed data unless you really, really, really do need to. All covered on the net. Google has lots and lots of info about this. This forum too.