sizeof(struct) 返回意外值
这应该很简单,但我不知道在哪里寻找问题:
我有一个结构:
struct region
{
public:
long long int x;
long long int y;
long long int width;
long long int height;
unsigned char scale;
};
当我执行 sizeof(region)
时,当我期待时,它会给我 40 33。
有什么想法吗?
(mingw gcc,win x64 操作系统)
This should be simple but I have no clue where to look for the issue:
I have a struct:
struct region
{
public:
long long int x;
long long int y;
long long int width;
long long int height;
unsigned char scale;
};
When I do sizeof(region)
it gives me 40 when I am expecting 33.
Any ideas?
(mingw gcc, win x64 os)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它填充结构以适应 8 字节边界。所以它实际上在内存中占用了 40 个字节 - sizeof 返回了正确的值。
如果您希望它只占用 33 个字节,请指定
packed
属性:It's padding the struct to fit an 8-byte boundary. So it actually is taking 40 bytes in memory - sizeof is returning the correct value.
If you want it to only take 33 bytes then specify the
packed
attribute:long long int
值每个为 8 个字节。scale
只有 1 个字节,但为了对齐而进行了填充,因此它实际上也占用了 8 个字节。 5*8 = 40。long long int
values are 8 bytes each.scale
is only 1 byte but is padded for alignments, so it effectively takes up 8 bytes too.5*8 = 40
.正如其他人所说,结构体是为了对齐而进行填充的,这种填充不仅取决于成员的类型,还取决于它们所在的成员的顺序定义的。
例如,考虑如下定义的这两个结构体
A
和B
。两个结构体在成员和类型方面是相同的;唯一的区别是定义成员的顺序不同:sizeof(A)
是否等于sizeof(B)
只是因为它们相同相同类型的成员数量?不。尝试打印每个的大小:输出:
惊讶吗?自己查看输出:http://ideone.com/yCX4S
As others said, structs are padded for alignments, and such padding not only depends on the type of the members, but also on the order of the members in which they're defined.
For example, consider these two structs
A
andB
as defined below. Both structs are identical in terms of members and types; the only difference is that the order in which members are defined isn't same:Would the
sizeof(A)
be equal tosizeof(B)
just because they've same number of members of same type? No. Try printing the size of each:Output:
Surprised? See the output yourself : http://ideone.com/yCX4S