gpt4 book ai didi

c - 使用 C 中的结构 union

转载 作者:太空狗 更新时间:2023-10-29 17:19:13 25 4
gpt4 key购买 nike

假设我有以下类型:

typedef struct TYPEA
{
int type;
char[12] id;
} TYPEA;

typedef struct TYPEB
{
int type;
int value;
} TYPEB;

我想使用创建这些类型和“int”的 union ,这样我就可以访问“类型”int 而无需知道 TYPEA 或 TYPEB 是否存储在 union 中(int 的值让我确定哪个实际上存储在那里)。虽然我无法获得正确的语法。

我的联盟:

typedef union MEMBER
{
int type;
struct TYPEA a;
struct TYPEB b;
} MEMBER;

union 通过以下方式访问:

typedef struct WRAPPER
{
union MEMBER* member;
struct WRAPPER* next;
} WRAPPER;

问题:

  1. (将“w”作为指向分配的 WRAPPER 结构的指针)使用 w->member->a.id 进行访问会在非结构或 union 的内容中给出“对成员‘id’的请求” .
  2. 我可以将一个指向已分配的 TYPEA/B 的指针直接分配给 w->member 吗?还是 union 需要特别分配?

谢谢。

最佳答案

  1. 使用w->member->type
  2. 您需要专门分配union

可能会引起误解的一点是,union 包含 intTYPEATYPEB ,所以特别是你不能依赖 union 中的 int type; 来告诉你 union 持有哪个 struct

编辑以回复评论中的问题:

你可能想要这样的东西:

struct TYPEA {
char data[30]; // or whatever
};

struct TYPEB {
double x, y; // or whatever
};

struct some_info {
int type; // set accordingly
union {
struct TYPEA a;
struct TYPEB b;
} data; // access with some_info_object.data.a or some_info_object.data.b
};

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

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