与内存对齐有关的sizeof

本文通过多个实例演示了不同编译器指令下结构体内存对齐的原理与效果,包括默认对齐、#pragmapack(1)、#pragmapack(2)和#pragmapack(3)的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       内存对齐, 大家应该都听说过, 我们直接来看程序:

 

#include <iostream>
using namespace std;

struct 
{
	int a;
	short b;
}A;

struct 
{
	short b;
	int a;
}B;

struct 
{
	short b;
	short c;
	int a;
}C;

struct 
{
	bool b;
	bool c;
	int a;
}D;

struct 
{
	bool c;
	int a;
	bool b;
}E;

struct 
{
	double a;
	int b;
	float c;
	char d;
	char f;
}F;

int main()
{
	cout << sizeof(A) << endl; // 8
	cout << sizeof(B) << endl; // 8
	cout << sizeof(C) << endl; // 8
	cout << sizeof(D) << endl; // 8
	cout << sizeof(E) << endl; // 12
	cout << sizeof(F) << endl; // 24

	return 0;
}

 

 

      继续看:

 

#include <iostream>
using namespace std;

#pragma pack(1)

struct 
{
	int a;
	short b;
}A;

struct 
{
	short b;
	int a;
}B;

struct 
{
	short b;
	short c;
	int a;
}C;

struct 
{
	bool b;
	bool c;
	int a;
}D;

struct 
{
	bool c;
	int a;
	bool b;
}E;

struct 
{
	double a;
	int b;
	float c;
	char d;
	char f;
}F;

int main()
{
	cout << sizeof(A) << endl; // 6
	cout << sizeof(B) << endl; // 6
	cout << sizeof(C) << endl; // 8
	cout << sizeof(D) << endl; // 6
	cout << sizeof(E) << endl; // 6
	cout << sizeof(F) << endl; // 18

	return 0;
}


      继续看:

 

 

#include <iostream>
using namespace std;

#pragma pack(2)

struct 
{
	int a;
	short b;
}A;

struct 
{
	short b;
	int a;
}B;

struct 
{
	short b;
	short c;
	int a;
}C;

struct 
{
	bool b;
	bool c;
	int a;
}D;

struct 
{
	bool c;
	int a;
	bool b;
}E;

struct 
{
	double a;
	int b;
	float c;
	char d;
	char f;
}F;

int main()
{
	cout << sizeof(A) << endl; // 6
	cout << sizeof(B) << endl; // 6
	cout << sizeof(C) << endl; // 8
	cout << sizeof(D) << endl; // 6
	cout << sizeof(E) << endl; // 8
	cout << sizeof(F) << endl; // 18

	return 0;
}


     继续看:

 

 

#include <iostream>
using namespace std;

#pragma pack(3)

struct 
{
	int a;
	short b;
}A;

struct 
{
	short b;
	int a;
}B;

struct 
{
	short b;
	short c;
	int a;
}C;

struct 
{
	bool b;
	bool c;
	int a;
}D;

struct 
{
	bool c;
	int a;
	bool b;
}E;

struct 
{
	double a;
	int b;
	float c;
	char d;
	char f;
}F;

int main()
{
	cout << sizeof(A) << endl; // 8
	cout << sizeof(B) << endl; // 8
	cout << sizeof(C) << endl; // 8
	cout << sizeof(D) << endl; // 8
	cout << sizeof(E) << endl; // 12
	cout << sizeof(F) << endl; // 24

	return 0;
}

       此时, 我们得到 warning C4086: expected pragma parameter to be '1', '2', '4', '8', or '16'

 

 

        好吧, 消化了上面的程序, 内存对其基本算是入门了。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值