gpt4 book ai didi

c - C 中的结构扩展

转载 作者:行者123 更新时间:2023-12-05 02:05:26 24 4
gpt4 key购买 nike

假设定义了 2 个结构,例如:

typedef struct {
T x;
T y;
} A;

typedef struct {
A a;
T z;
} B;

我可以将指向结构 B 的指针视为指向结构 A 的指针吗?

在实践中这是可靠的/标准的/可移植的/编译器不变的:

B b = {{1,2},3};
A * a = &b;

print(a->x);
print(a->y);

最佳答案

C17 6.7.2.1 声明了这一点(强调我的):

Within a structure object, the non-bit-field members and the units in which bit-fieldsreside have addresses that increase in the order in which they are declared. A pointer to astructure object, suitably converted, points to its initial member (or if that member is abit-field, then to the unit in which it resides), and vice versa.

这意味着您必须将 B b 对象的指针“适本地转换”为它的第一个成员的类型。这种转换不会隐式发生,您必须通过显式转换来完成:

A * a = (A*)&b;

根据上面引用的部分,这样做是明确且安全的。

同样,不允许编译器假设指向A 的指针和指向B 的指针不存在别名。有效类型规则 6.5.7(“严格别名”)给出了这种情况的异常(exception)情况:

An object shall have its stored value accessed only by an lvalue expression that has one of the following types:
...

  • an aggregate or union type that includes one of the aforementioned types among its members

例如,在优化期间调用函数 void func (B* b) 的编译器不允许假定外部连接变量 extern A a; 定义在一些其他的翻译单元没有被函数改变。

关于c - C 中的结构扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63518693/

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