gpt4 book ai didi

c - 访问不同结构的相同成员

转载 作者:太空宇宙 更新时间:2023-11-04 02:27:03 27 4
gpt4 key购买 nike

免责声明:以下是尽量简化问题。最初变量 int x 是一个结构,但我认为这在这里并不重要。

假设我们在一个 union 中有两个结构(我对此没有影响)

typedef struct a_t {
int x;
int irrelevant;
} a_;

typedef struct b_ {
float also_irrelevant;
int x;
} b_;

typedef union uni_t{
a_ a;
b_ b;
} uni;

是否可以通过像 ptr_to_struct->x 这样的相同语句在两个结构中访问 x?但是 afaik 指针在编译时需要正确的类型。所以一个类似于这个伪代码的依赖声明

if (union contains a_)
{
a_ * ptr_to_struct; // but outside of this scope
ptr_to_struct = &(uni.a);
}
else
{
b_ * ptr_to_struct; // but outside of this scope
ptr_to_struct = &(uni.b);
}

据我所知这是不可能的。

是否有可能独立于联盟的当前状态获得对变量 x 的“一般”访问权限?

最佳答案

你是对的,这是不可能的。 ptr_to_struct 的类型在这里是次要问题。主要问题是 unix 的地址根据 union 中哪个 struct 是“活跃的”而变化>:

  • 如果 a_ 为“active”,则 xunion 顶部的偏移量为零
  • 如果 b_ 为“active”,则 xunion 顶部的偏移量为 sizeof(float) 加上可能的额外字段对齐偏移量

这个问题的一个解决方案是将 x 放在两个 struct 的初始字段序列中的相同位置:

typedef struct a_t {
int x;
int irrelevant;
} a_;

typedef struct b_t {
int x; // Moved to the top
float also_irrelevant;
} b_;

现在 x 占据相同的位置,C makes a guarantee如果您通过 a.x 或通过 b.x 访问它, union 中 x 的地址将是相同的。

关于c - 访问不同结构的相同成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49533740/

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