struct str2_t { unsigned short s; unsigned int i; unsigned char c; }str2;
你们猜sizeof(str2)等于多少?是9还是7?但是我实际运行的时候是12.很不解。 C struct [解决办法] 会有内存对齐的问题,紧凑的排放用#param pack(1)修饰。
[解决办法] 运行一下,分析结果(提示: 内存对齐+结构体成员补齐)
#include <stdio.h>
typedef struct str2_t { unsigned short s; unsigned int i; unsigned char c; }str2;
int main() { str2 o; printf("start of s: %p, end of s: %p\n", &o.s, &o.s+1); printf("start of i: %p, end of i: %p\n", &o.i, &o.i+1); printf("start of c: %p, end of c: %p\n", &o.c, &o.c+1); printf("start of o: %p, end of o: %p\n", &o, &o+1); return 0; }
[解决办法] 我觉得是内存对齐的问题, 在 struct str2_t { unsigned short s; unsigned int i; unsigned char c; }str2; 里面,再加一个unsigned char c2;sizeof(str2)还是12,后面补两个0; 是这样对齐的