sizeof的工会大于预期。如何式排列发生在这里? [英] sizeof union larger than expected. how does type alignment take place here?
本文介绍了sizeof的工会大于预期。如何式排列发生在这里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
union u1 {
struct {
int *i;
} s1;
struct {
int i, j;
} s2;
};
union u2 {
struct {
int *i, j;
} s1;
struct {
int i, j;
} s2;
};
int main(void) {
printf(" size of int: %zu\n", sizeof(int));
printf("size of int pointer: %zu\n", sizeof(int *));
printf(" size of union u1: %zu\n", sizeof(union u1));
printf(" size of union u2: %zu\n", sizeof(union u2));
return 0;
}
结果是:
$ gcc -O -Wall -Wextra -pedantic -std=c99 -o test test.c
$ ./test
size of int: 4
size of int pointer: 8
size of union u1: 8
size of union u2: 16
为什么加入4字节工会U2的嵌套结构S1的整8个字节增加了工会作为一个整体的尺寸?
Why does adding an integer of 4 bytes to nested struct s1 of union u2 increase the size of the union as a whole by 8 bytes?
推荐答案
该结构 u2.s2
是因为对齐约束16个字节。编译器保证,如果你做出这样结构的数组,每个指针将在8字节边界上对齐。字段 *我
需要8个字节,那么Ĵ
需要4个字节,编译器插入4字节的填充。因为结构是16个字节,包含它的工会也是16字节。
The struct u2.s2
is 16 bytes because of alignment constraints. The compiler is guaranteeing that if you make an array of such structs, each pointer will be aligned on an 8-byte boundary. The field *i
takes 8 bytes, then j
takes 4 bytes, and the compiler inserts 4 bytes of padding. Because the struct is 16 bytes, the union containing it is also 16 bytes.
这篇关于sizeof的工会大于预期。如何式排列发生在这里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文