C/C++结构体对齐规则

发表于:2014-3-19 09:48

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:XiaoMaoLV90    来源:51Testing软件测试网采编

  C++中有个pragma pack 会对对齐方式进行改变
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#pragma pack(push) //保存对齐状态
#pragma pack(4)//设定为4字节对齐
struct TEST0
{
char m1;
double m4;
int m3;
};
#pragma pack(pop)//恢复对齐状态
#pragma pack(push)
#pragma pack(2)<span style="white-space:pre">   </span>//#pragma pack(1)会有不同的结果
struct TEST1    //12
{
char a;
int b;
char c;
};
#pragma pack(pop)
struct TEST2    //8
{
char a;
char b;
int c;
};
struct TEST3    //8
{
char a;
char b;
char c;
int d;
};
struct TEST4    //12
{
char a[5];
int b;
};
struct TEST5    //8 + 8 + 8 = 24
{
double a; //8
char b; //4
int c; //4,location the b memery
char d[5]; //5
};
int _tmain(int argc, _TCHAR* argv[])
{
struct TEST0 t0;
cout << sizeof(t0) << endl;
struct TEST1 t1;
struct TEST2 t2;
struct TEST3 t3;
struct TEST4 t4;
struct TEST5 t5;
cout << sizeof(t1) << endl << sizeof(t2) << endl;
cout << sizeof(t3) << endl << sizeof(t4) << endl << sizeof(t5) << endl;
return 0;
}
  可以简单这样理解 要么按照默认对齐,要么按照pack里面的数值进行对齐
  对TEST1 pack里面值为1与2会有不同结构
  当为1时,占用6个字节
  a b1 b2 b3
  b4 c
  当为2时, 占用8个字节
  a ax b1 b2
  b3 b4 c cx
22/2<12
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号