Why is my union's size bigger than I expected?

前端 未结 5 1686
滥情空心
滥情空心 2021-01-18 06:13

When I print the size of a union like this:

union u {
  char c[5];
  int i;
} un;

using this:

int _tmain(int argc, _TCHAR*          


        
5条回答
  •  孤城傲影
    2021-01-18 06:53

    The compiler can add padding wherever it wants to structs, unions, and classes to speed memory accesses. You are seeing the effect of that. For Visual C++, the padding is usually a multiple of the size of the largest member type. In this instance, the largest member is an int, therefore it pads the union with 3 unused bytes to make the total size 8.

提交回复
热议问题