C++高效编程笔记2:struct中的字节对齐
2007-01-13 14:56
507 查看
#include <iostream.h>
structA{
chara;longb;charc;longd;
};
structB{
chara;charc;longb;longd;
};
#pragma pack(push, 1)
structC{
chara;longb;charc;longd;
};
#pragma pack(pop)
structD{
char*a;char*b;
};
//使用比特域的结构
structBitField{
unsigneda1:11; //long 1
unsigneda2:11;
unsignedb1:10;
unsigneda3:11; //long 2
unsigneda4:11;
unsignedb2:10;
};
voidmain(void)
{
cout<<"Size of A : "<<sizeof(A)<<"bytes"<<endl;
cout<<"Size of B : "<<sizeof(B)<<"bytes"<<endl;
cout<<"Size of C : "<<sizeof(C)<<"bytes"<<endl;
cout<<"Size of D : "<<sizeof(D)<<"bytes"<<endl;
cout<<"Size of BitField : "<<sizeof(BitField)<<"bytes"<<endl;
}
运行结果:
Size of A : 16bytes
Size of B : 12bytes
Size of C : 10bytes
Size of D : 8bytes
Size of BitField : 8bytes
A、B、C之所以不一样是因为字节对齐的问题。#pragma pack(push, 1)指令可以让编译器暂时调整对齐,设置为1字节。
另外注意,char * 一般占4字节。
structA{
chara;longb;charc;longd;
};
structB{
chara;charc;longb;longd;
};
#pragma pack(push, 1)
structC{
chara;longb;charc;longd;
};
#pragma pack(pop)
structD{
char*a;char*b;
};
//使用比特域的结构
structBitField{
unsigneda1:11; //long 1
unsigneda2:11;
unsignedb1:10;
unsigneda3:11; //long 2
unsigneda4:11;
unsignedb2:10;
};
voidmain(void)
{
cout<<"Size of A : "<<sizeof(A)<<"bytes"<<endl;
cout<<"Size of B : "<<sizeof(B)<<"bytes"<<endl;
cout<<"Size of C : "<<sizeof(C)<<"bytes"<<endl;
cout<<"Size of D : "<<sizeof(D)<<"bytes"<<endl;
cout<<"Size of BitField : "<<sizeof(BitField)<<"bytes"<<endl;
}
运行结果:
Size of A : 16bytes
Size of B : 12bytes
Size of C : 10bytes
Size of D : 8bytes
Size of BitField : 8bytes
A、B、C之所以不一样是因为字节对齐的问题。#pragma pack(push, 1)指令可以让编译器暂时调整对齐,设置为1字节。
另外注意,char * 一般占4字节。
相关文章推荐
- 笔记——struct之字节对齐
- C++ 字节对齐(class 与struct)
- C/C++中的struct字节对齐问题
- C++ 字节对齐分析,struct成员指定位大小
- C++ 学习笔记3,struct长度測试,struct存储时的对齐方式
- C++ 学习笔记3,struct长度測试,struct存储时的对齐方式
- C++ 学习笔记3,struct长度测试,struct存储时的对齐方式
- C++高效编程:阅读笔记1
- 【C/C++】struct探索·extern "C"含义探索 ·C++与C的混合编程·C 语言高效编程的几招
- c/c++ struct 字节对齐
- [收藏转贴]struct探索·extern "C"含义探索 ·C++与C的混合编程·C 语言高效编程的几招
- c++ 面向对象高效编程 【笔记】什么是面向对象编程?
- (c/c++学习笔记三) 结构体与联合体的字节对齐
- C++:struct和union 内存字节对齐问题
- 深入剖析C++中的struct结构体字节对齐
- 【C++学习笔记】sizeof()的用法与字节对齐
- c++内存中字节对齐问题详解 [ 转载 ]
- c/c++ struct内存对齐
- C++高质量编程指南笔记(四)
- struct 字节对齐详解与大小端模式