gpt4 book ai didi

c++ - struct hack - 大小为零的数组

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

#include <iostream>
using namespace std;

struct node1{
char b[3];
int c[0];
};

struct node2{
int c[0];
};

struct node3{
char b[3];
};


int main() {

cout << sizeof(node1) << endl; // prints 4
cout << sizeof(node2) << endl; // prints 0
cout << sizeof(node3) << endl; // prints 3
}

我的问题是为什么编译器在 node2 中为 int c[0] 分配 0 字节但为其 when 节点 1 的一部分分配 1 个字节。我假设这 1 个字节是 sizeof(node1) 返回 4 的原因,因为没有它(就像在 node3 中)它的大小是 3 还是由于填充?

还试图理解 node2 不应该有足够的空间来保存指向数组的指针(作为灵活数组/结构 hack 的一部分,它将在代码的更下方分配?

最佳答案

是的,这是关于填充/对齐的。如果您将 __attribute__((__packed__)) 添加到末尾 [在编写设备驱动程序时很有用],您的输出将得到 3 0 3

如果 node1 定义了 c[1],则大小为 8 而不是 7,因为编译器会将 c 对齐到 int 边界。打包后,sizeof 将为 7

关于c++ - struct hack - 大小为零的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246949/

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