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

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

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

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

  1.基本理解
  比如:struct TEST
  {
  char a;
  int b;
  char c;
  }
  那么经过sizeof后得出结果是 12, 因为默认内存占用4byte, 变量a占用1byte,剩下3个,不足以存放变量b,故变量a也占用了4byte, 变量c由于后面没有了数据, 也会变为4byte,最后sizeof值为12。
#include "stdafx.h"
#include <iostream>
using namespace std;
struct TEST1    //12
{
char a;
int b;
char c;
};
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 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;
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

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

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

沪ICP备05003035号

沪公网安备 31010102002173号