c - C结构对齐

扫码查看

我在试着理解结构是如何排列的。根据this source,我本以为

#include<inttypes.h>
#include<stdio.h>

typedef struct {
  uint16_t a;
  uint16_t b;
  uint32_t c;
} test_struct;

int main (int argc, char const *argv[])
{
  printf("%lu\n", sizeof(test_struct));
  return 0;
}

大小为12字节。在我的例子中只需要8个字节。因为它包含一个32位整数,所以我认为它应该与4字节对齐,显然不是这样。
环顾四周后,我发现这个this answer意味着不仅仅是成员本身需要结盟。
这完全解释了我的结构的大小,但是这与我的第一个声称“结构实例将拥有其最宽标量成员的对齐”的源代码是如何对齐的呢?是错了还是我遗漏了什么?

最佳答案

你的两个消息来源都是正确的。

typedef struct {
uint16_t a; // 2 bytes
uint16_t b; // 2 bytes
uint32_t c; // 4 bytes
} test_struct;

结构的总大小为8字节。为了确定是否需要填充,我们检查最宽的标量成员(4字节)并检查该数字是否可以被不带填充的总大小整除。
8 % 4 == 0
所以我们不需要填充。
如果我们有:
typedef struct {
uint16_t a; // 2 bytes
uint16_t b; // 2 bytes
uint32_t c; // 4 bytes
uint16_t d; // 2 bytes
} test_struct;

总大小:10字节
12 % 4 == 2
需要填充:2字节
实际总大小:12字节

10-04 20:56
查看更多