gpt4 book ai didi

c++ - 为什么 offsetof(member) 等于 sizeof(struct)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:45 30 4
gpt4 key购买 nike

我有一个结构定义为:

struct smth
{
char a;
int b[];
};

当我在此结构上调用 sizeofoffsetof 时:

cout << sizeof(struct smth) << endl;
cout << offsetof(struct smth, b) << endl;

输出是:

4
4

为什么stuct的大小是4,char占用1个字节,int数组的偏移量是4?为什么会有某种填充?另外,为什么 int 数组根本不占用任何空间?

最佳答案

How come when the size of the stuct is 4 and char is using 1 byte, the offset of the int array is 4? Why is there some kind of padding?

有填充是因为C标准允许;编译器经常对齐变量以提高性能。

Also, why isn't the second variable occupying any space at all (which seems like the case)?

它是一个 C99 灵活数组成员——这就是它的全部意义所在。这个想法是分配你的结构是这样的:

struct smth *s = malloc(sizeof *s + 10 * sizeof s->b[0]);

然后您将拥有一个结构,其运行方式就好像 b 是一个 10 元素数组。

关于c++ - 为什么 offsetof(member) 等于 sizeof(struct)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18290247/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com