使用 C 中的结构联合 [英] Working with a union of structs in C

查看:24
本文介绍了使用 C 中的结构联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下类型:

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

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

我想使用创建这些类型和int"的联合,这样我就可以访问类型"int,而无需知道联合中存储的是 TYPEA 还是 TYPEB(int 的值让我确定哪个实际上存储在那里).但我无法获得正确的语法.

I want to use create a union of these types and 'int', so that I can access the "type" int without needing to know whether TYPEA or TYPEB is stored in the union (the value of int lets me determine which is actually stored there). I can't get the right syntax though.

我的工会:

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

通过以下方式访问联合:

The union is accessed via:

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

问题:

  1. (使用 'w' 作为指向分配的 WRAPPER 结构的指针)使用 w->member->a.id 访问会在非结构体中提供对成员 'id' 的请求或工会.
  2. 我可以将一个指向已被 malloc 的 TYPEA/B 的指针直接分配给 w->member 吗?或者联合需要特别malloced?
  1. (With 'w' as a pointer to an allocated WRAPPER struct) Accessing using w->member->a.id gives "request for member 'id' in something not a structure or union.
  2. Can I assign a pointer to an already malloc'd TYPEA/B to w->member directly? Or does a union need to be malloced specially?

谢谢.

推荐答案

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

一个可能引起误解的注释是 union 持有 intTYPEATYPEB,所以特别是你不能依靠联合中的 int type; 来告诉你联合持有哪个 struct.

One note that may be a point of misunderstanding is that the union holds EITHER the int, or TYPEA, or TYPEB, so in particular you cannot rely on your int type; in the union to tell you which struct the union holds.

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

你可能想要这样的东西:

You probably want something like this:

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 中的结构联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆