带联合的 sizeof 结构 [英] sizeof struct with union
本文介绍了带联合的 sizeof 结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对整个数据对齐"的事情感到非常困惑:
#include int main(){结构体{int i,*p;字符 c;联合{字符类型[4];无符号字符 d;} un;};struct st s1={25,&a,'X',"asdf"};printf("s1 的大小是 %d",sizeof(s1));返回0;}
由于数据对齐,我认为由于
的大小int i : 4 字节int *p : 8 字节字符 c : 1 字节 (+3)联合:4 个字节
输出将是 20,但这输出 sizeof s1 是 24
!为什么输出24?这是否考虑到 int *p,即 8 个字节?
解决方案
在您的系统上,指针是 8 个字节并对齐到 8 个字节.
<前>1 2 3 4 5 6 7 8+---+---+---+---+---+---+---+---+---+|国际 |[垫] |+---+---+---+---+---+---+---+---+---+9 10 11 12 13 14 15 16+---+---+---+---+---+---+---+---+---+|整数 *p |+---+---+---+---+---+---+---+---+---+17 18 19 20 21 22 23 24+---+---+---+---+---+---+---+---+---+|| |联合国 |[垫] |+---+---+---+---+---+---+---+---+---+当然,如果不了解 ABI,您就无法确定确切的布局.以上只是一个例子.
I'm very confused by the whole 'data alignment' thing:
#include <stdio.h>
int main(){
struct st{
int i,*p;
char c;
union { char type[4]; unsigned char d;} un;
};
struct st s1={25,&a,'X',"asdf"};
printf("sizeof s1 is %d",sizeof(s1));
return 0;
}
due to data alignment, i thought that since the sizes of
int i : 4 bytes
int *p : 8 bytes
char c : 1 byte(+3)
union : 4 bytes
the output would be 20, but this outputs sizeof s1 is 24
!
Why is it outputting 24? Does this regard int *p, which is 8 bytes?
解决方案
On your system, pointers are 8 bytes and aligned to 8 bytes.
1 2 3 4 5 6 7 8 +---+---+---+---+---+---+---+---+ | int i | [pad] | +---+---+---+---+---+---+---+---+ 9 10 11 12 13 14 15 16 +---+---+---+---+---+---+---+---+ | int *p | +---+---+---+---+---+---+---+---+ 17 18 19 20 21 22 23 24 +---+---+---+---+---+---+---+---+ | c | un | [pad] | +---+---+---+---+---+---+---+---+
Of course, you cannot be sure of the exact layout without knowing the ABI. The above is only an example.
这篇关于带联合的 sizeof 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文