结构大小与 typedef 版本不同? [英] struct size is different from typedef version?
问题描述
我的代码中有以下结构声明和 typedef:
I have the following struct declaration and typedef in my code:
struct blockHeaderStruct {
bool allocated;
unsigned int length;
};
typedef struct blockHeaderStruct blockHeader;
当我做 sizeof(blockheader)
时,我得到了 4 个字节的值,但是当我做 sizeof(struct blockHeaderStruct)
时,我得到了 8 个字节.
When I do sizeof(blockheader)
, I get the value of 4 bytes back, but when I do sizeof(struct blockHeaderStruct)
, I get 8 bytes.
为什么会这样?为什么我不拿回 5?
Why is this happening? Why am I not getting 5 back instead?
推荐答案
查看结构的定义,您有 1 个字节的值,后跟 4 个字节的整数.这个整数需要在 4 字节边界上分配,这将强制编译器在 1 字节 bool 之后插入 3 字节填充.这使得 struct 的大小为 8 字节.为了避免这种情况,您可以更改结构中元素的顺序.
Looking at the definition of your struct, you have 1 byte value followed by 4 byte Integer. This integer needs to be allocated on 4 byte boundary, which will force compiler to insert a 3 byte padding after your 1 byte bool. Which makes the size of struct to 8 byte. To avoid this you can change order of elements in the struct.
另外,对于返回不同值的两个 sizeof 调用,您确定这里没有打字错误,并且您没有获取指针或不同类型或某些整数变量的大小.
Also for two sizeof calls returning different values, are you sure you do not have a typo here and you are not taking size of pointer or different type or some integer variable.
这篇关于结构大小与 typedef 版本不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!