10713
题目
编写程序演示联合体的内存布局,计算并输出不同联合体类型的大小,验证内存对齐的影响。
答案
c
#include <stddef.h>
#include <stdio.h>
union small {
char c;
int i;
};
union mixed {
char c;
double d;
int i;
};
struct wrapper {
char tag;
union mixed value;
};
int main(void) {
printf("sizeof(union small) = %zu\n", sizeof(union small));
printf("sizeof(union mixed) = %zu\n", sizeof(union mixed));
printf("sizeof(struct wrapper) = %zu\n", sizeof(struct wrapper));
printf("offsetof(value) = %zu\n", offsetof(struct wrapper, value));
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
联合体的大小至少能容纳最大的成员,同时还要满足最严格成员的对齐要求。struct wrapper 中 value 前面可能出现填充字节,这可以通过 offsetof 观察。