10 years, 6 months ago.

struct size problem

Hi I have a code:

  1. include "mbed.h"

struct MBAP_TYPE { uint16_t T_ID; uint16_t P_ID; uint16_t LENGTH; uint8_t U_ID; };

int main() { printf("SIZES %d %d %d \r\n",sizeof(uint8_t),sizeof(uint16_t),sizeof(MBAP_TYPE)); }

Anyone could explain me, why "sizeof(MBAP_TYPE)" give me value 8, not 7 ?

Regards Serge

2 Answers

10 years, 6 months ago.

I don't have an mbed currently here to test it, but I guess it is related to the allignment of variables by the compiler. Placing the uint8_t at the beginning of the struct might already make a difference.

10 years, 6 months ago.

Thanks Erik, But this way doesn't work and don't solve my problem, because I would like to use this structure in union with byte array.

Well then you can still do a union, but the order is different, U_ID is then the first byte.

You can also force the compiler to remove the allignment, see: http://mbed.org/forum/bugs-suggestions/topic/4264/. However then at the same time at least non-properly aligned floats apparantly can crash your microcontroller. You don't have floats, but I would rather have overhead of one byte.

posted by Erik - 05 Nov 2013

Thanks Erik, After removing alignment, program works correctly.

posted by Katunin Serge 05 Nov 2013