69,382
社区成员
发帖
与我相关
我的任务
分享
Yes!
#include <iostream>
using namespace std;
//#pragma pack(1) //使用#pragma pack可以将对齐设置为1
/*
内存对齐的3个准则:
1、结构体变量的首地址能够被其最宽的基本类型成员大小所整除
2、结构体每个成员相对于结构体首地址的偏移量(offset)都是这个成员大小的整数倍,如有不足则补上
3、结构体总大小为结构体最宽的基本类型成员的整数倍
*/
struct widget1
{
double d; //sizeof(double)== 8
int i; //sizeof(int) == 4
short s; //sizeof(short) == 2
char c; //sizeof(char) == 1
static int count; //count是静态成员,静态成员的空间不在类的实例中,
//而是像全局变量一样在静态存储区,被类共享。
};
int widget1::count = 0;
/*
对于widget1:
d的偏移量为0;
i的偏移量为8,是sizeof(int)的整数倍,不需补字节
s的偏移量为8+4=12,是sizeof(short)的整数倍,不需补字节
c的偏移量为8+4+2=14,是sizeof(char)的整数倍,不需补字节
目前的结构体的字节数为8+4+2+1=15,不是最大基本变量d大小的整数倍,需要补上1字节,15+1=16
所以sizeof(widget1)==16
*/
struct widget2
{
int i; //sizeof(int) == 4
short s; //sizeof(short) == 2
char c; //sizeof(char) == 1
double d; //sizeof(double)== 8
};
/*
对于widget2:
i的偏移量为0
s的偏移量为4,是sizeof(short)的整数倍,不需补字节数
c的偏移量为4+2=6,也不需补字节数
d的偏移量为4+2+1=7,但不是sizeof(double)的整数倍,要补字节数1,
所以d的偏移量为4+2+1+1(补齐)=8
目前结构体的字节数为4+2+1+1(补齐)+8=16,是最大基本变量d大小的整数倍,不需补齐
所以sizeof(widget2)==16
*/
struct widget3
{
char c; //sizeof(char) == 1
int i; //sizeof(int) == 4
short s; //sizeof(short) == 2
double d; //sizeof(double)== 8
};
/*
对于widget2:
c的偏移量为0
i的偏移量为1(c的大小)+3(补齐)=4
s的偏移量为1(c的大小)+3(补齐)+4(i的大小)=8
d的偏移量为1(c的大小)+1(补齐)+4(i的大小)+2(s的大小)+6(补齐)=16
目前结构体的大小为1(c的大小)+1(补齐)+4(i的大小)+2(s的大小)+6(补齐)+8(d的大小)=24,不需补齐
所以sizeof(widget3)=24
*/
int main()
{
cout<<"the size of widget is: "<<sizeof(widget1)<<endl;
cout<<"the size of widget is: "<<sizeof(widget2)<<endl;
cout<<"the size of widget is: "<<sizeof(widget3)<<endl;
system("pause");
return 0;
}
#include "stdio.h"
#pragma pack(4)
struct s
{
char id;
char number;
int age;
};
int main()
{
printf("sizeof(struct s) = %d\n", sizeof(struct s)) ;
}
前面是两个char类型,加起来是两个字节(为什么不用补齐,参照第一个原则)
最后一个int类型所占是四个字节,而前面只有两个字节,不是4的整数倍,所以补齐,所以加起来总长度就是2+2+4=8
第二个为什么是12你应该会明白了吧O(∩_∩)O~