Appearance
38 对象布局 · 对齐、填充与线上格式
用 offsetof 观察成员位置,再显式写入三个协议字节。结构体占用的内存由 ABI 决定。
源码
main.c
c
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
typedef struct {
uint8_t type;
uint16_t seq;
} Header;
_Static_assert(offsetof(Header, type) == 0, "first member offset");
static void encode(uint8_t out[3], const Header *h)
{
out[0] = h->type;
out[1] = (uint8_t)(h->seq >> 8);
out[2] = (uint8_t)h->seq;
}
int main(void)
{
Header h = {.type = 0x2A, .seq = 0x1234};
uint8_t wire[3];
encode(wire, &h);
printf("%02X %02X %02X\n", (unsigned)wire[0], (unsigned)wire[1], (unsigned)wire[2]);
return 0;
}主机运行
在仓库根目录执行。Windows 可以将输出名写成 reading-38.exe,再从终端运行。
sh
gcc -std=c11 -Wall -Wextra -pedantic examples/c-reading/38/main.c -o reading-38
./reading-38先沿 main() 预测打印结果,再展开核对。
主机输出与手推
text
2A 12 34类型 2A、序号 1234 要发送的三个字节是 2A 12 34。结构体的成员偏移可以因平台改变。
练习
用 printf 打印 sizeof(Header)、_Alignof(Header) 和 offsetof(Header, seq),再换编译目标比较。
验证记录
主机版使用 GCC 编译运行,输出与跟读材料逐项核对。