为什么这个结构体的大小是24 ?
Why is the size of this struct 24?
我有一个结构体,我想计算它的大小:
#pragma pack(push,4)
struct MyStruct
{
uint32_t i1; /* size=4, offset=0. */
uint32_t i2; /* size =4 offset =4 */
uint16_t s1; /* size =2 offset=8 */
unsigned char c[8]; /* size=8 offset=12*/
uint16_t s2; /* size=2 offset=20. */
uint16_t s3; /* size=2 offset=24. */
} ; // total size is 26
static_assert(sizeof(MyStruct) == 24, "size of MyStruct incorrect");
#pragma pack(pop)
静态断言显示大小为24,但我的计算显示它应该是26。
为什么是24码?
我正在使用visual studio 2012开发windows 7, 32位应用程序
uint16_t
的对齐只有2,因此偏移量为:
#pragma pack(push,4)
struct MyStruct
{
uint32_t i1; /* offset=0 size=4 */
uint32_t i2; /* offset=4 size=4 */
uint16_t s1; /* offset=8 size=2 */
unsigned char c[8]; /* offset=10 size=8 */
uint16_t s2; /* offset=18 size=2 */
uint16_t s3; /* offset=20 size=2 */
/* offset=22 padding=2 (needed to align MyStruct) */
} ; // total size is 24
编辑为了确保
的所有元素MyStruct A[10]; // or
MyStruct*B = new MyStruct[10];
正确对齐。这要求sizeof(MyStruct)
是alignof(MyStruct)
的倍数。这里,sizeof(MyStruct)
=6* alignof(MyStruct)
.
任何struct
/class
类型总是填充到其对齐的下一个倍数。
除了沃尔特的答案,考虑自己抓这条鱼。您所需要的只是printf函数和简单的算术:
struct MyStruct ms;
printf("sizeof(ms): %zdn", sizeof(ms));
printf("i1t%tdn", (uint8_t*)&ms.i1 - (uint8_t*)&ms);
printf("i2t%tdn", (uint8_t*)&ms.i2 - (uint8_t*)&ms);
printf("s1t%tdn", (uint8_t*)&ms.s1 - (uint8_t*)&ms);
printf("c t%tdn", (uint8_t*)&ms.c - (uint8_t*)&ms);
printf("s2t%tdn", (uint8_t*)&ms.s2 - (uint8_t*)&ms);
printf("s3t%tdn", (uint8_t*)&ms.s3 - (uint8_t*)&ms);
(%zd
用于打印size_t
, %td
用于打印ptrdiff_t
)一个普通的%d
可能会在大多数系统上工作得很好。
sizeof(ms): 24
i1 0
i2 4
s1 8
c 10
s2 18
s3 20
4 4 2 8 2 2 -将包装为:
4 4 4 8 2 2 -最后两个组合在一起为4字节。第三项需要填充,最后一项和前一项不需要。
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 为什么结构体和类都存在于C++中
- 为什么这个c++函数是结构体
- 为什么这个结构体的大小是24 ?
- 为什么c++中的结构体可以比C中做更多的事情?
- 指向结构体作为函数参数的指针-为什么不更新其值
- c++位域结构体大小定义(为什么它被包装得更大?)
- 为什么结构体可以存储自己的大小?
- 为什么使用带可变模板参数的结构体同时实例化两个模板
- 为什么在链表中声明指向同一结构体的指针?
- 为什么这个结构体填充技巧有效?
- 为什么我的结构体成员没有使用"{}"正确初始化?
- 为什么Visual Studio没有优化结构体以获得最佳内存使用?
- 为什么boost作者在这里使用结构体而不是类?
- 为什么编译器不能像变量声明那样在结构体成员中设置 char[] = { .. } 的大小?
- 为什么对于同一结构体的不同成员,指向成员的指针的值总是相同的?