C/C++类/结构体内存遵循三个原则:
1) 结构体变量的首地址能够被其最宽基本类型成员的大小所整除;
2) 结构体每个成员相对于结构体首地址的偏移量(offset)都是成员自身大小的整数倍,如有需要编译器会在成员之间加上填充字节(internal adding);
3) 结构体的总大小为结构体最宽基本类型成员大小的整数倍,如有需要编译器会在最末一个成员之后加上填充字节(trailing padding)。
2) 结构体每个成员相对于结构体首地址的偏移量(offset)都是成员自身大小的整数倍,如有需要编译器会在成员之间加上填充字节(internal adding);
3) 结构体的总大小为结构体最宽基本类型成员大小的整数倍,如有需要编译器会在最末一个成员之后加上填充字节(trailing padding)。
这样就知道
struct{
} t1;
为什么sizeof(t1)是12字节而不是6字节了。
char a 1Byte 补齐
int b 4Byte
(因为b是4Byte,所以b的偏移地址一定要是4的整数倍,所以在a后面补齐3位)
char c 1Byte 补齐
(因为最长成员b是4Byte,所以整个结构体一定要是4 的倍数,所以c也要补齐,)
(因为最长成员b是4Byte,所以整个结构体一定要是4 的倍数,所以c也要补齐,)
一共12Byte
另外,可以对结构成员列表重新排列,让那些对于边界对齐要求最严格的成员首先出现,对边界要求最弱的成员最后出现,可以减少内存损失。
比如t1可改为
struct{
这样sizeof(t1)只有8字节。
int b 4Byte
4Byte
4Byte
4Byte
4Byte
4Byte
4Byte
char a 1Byte 补齐
char c 1Byte 补齐
char
对于在结构体中的结构体,
struct t{
char a;
int b;
char c;
};
struct{
int
a;
struct t t1;
char c
}t2;
此时考虑时还是将t1中拆成各基本类型处理,t1中最宽类型成员的整数倍如果在t2中最大,就作为t2中最宽类型处理。
上述t2占用,4+12(结构体t1)+1+3=20
而这个例子
struct
test1
{char a;
double
b;
char c;};
struct test2
{ int a1;
struct test1 t1;
char c1;};
struct test2
sizeof(test1)= 24
而
test1中最宽的是double 为8
test1中最宽的是double 为8
所以在test2中,a1和c1都按8位补齐。 所以sizeof(test2)=8+24+8=40
对于结构体中的指针
struct p
{
};
指针都是占用4个字节。addr和pr,pb都是一样的。一共12
int main()
{
struct{
char first;
char second;
}half;
printf(“%d\n %d\n”,&half.first,&half.second);
}
打印
1374264
1374265
说明first在低,second在高。
再看struct和union联合使用:
先看union
#include
<</span>stdio.h>
union
{
int i;
char x[2];
}a; void main()
{
a.x[0] =10;
a.x[1] =1;
printf(“%d“,a.i);
}
<</span>stdio.h>
union
{
int
char
}a; void
{
a.x[0]
a.x[1]
printf(“%d“,a.i);
}
这里10是十进制,转为二进制是A
01 0A
答案:266 (低位低地址,高位高地址,内存占用情况是Ox010A)
#include
int main()
{
union{
int i;
struct{
char first;
char second;
}half;
}number;
number.i=0x4241;
printf(“%c%c\n”, number.half.first, number.half.second);
number.half.first=’a’;
number.half.second=’b’;
printf(“%x\n”,number.i);
}
答案: AB
版权声明:本文为leexurui原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。