struct sizeof result not expected

前端 未结 4 943
挽巷
挽巷 2020-12-07 02:50

I have a a struct defined thusly:

typedef struct _CONFIGURATION_DATA {
    BYTE configurationIndicator;
    ULONG32 baudRate;
    BYTE stopBits;
    BYTE par         


        
相关标签:
4条回答
  • 2020-12-07 03:17

    Alignment.

    use

    #pragma pack(1)

    ...struct goes here...

    #pragma pack()

    I would also recommend reordering things, and if necessary padding then with RESERVED bytes, so that multi-byte integral types will be better aligned. This will make processing faster for tbe CPU, and your code smaller.

    0 讨论(0)
  • 2020-12-07 03:22

    The extra size you are measuring is the padding introduced by the compiler.

    Presumably, you are working on a 32 bits system, so you will have 3 bytes of padding between configurationIndicator and baudRate, and 3 more bytes of padding at the end of the struct.

    0 讨论(0)
  • 2020-12-07 03:25

    Change the order of the elements. Start with the ULONG, followed by the BYTEs. This will improve the struct's alignment in memory.

    0 讨论(0)
  • 2020-12-07 03:32

    This is due to padding, because on your platform, an ULONG32 apparently must be aligned on 4-byte boundaries. Since the start and end of the struct apparently also must be aligned, the first and last BYTE will be padded with 3 bytes each.

    0 讨论(0)
提交回复
热议问题