我想创建一个链表,但我希望数据字段是 int 或 float。我写了一些代码如下:
union int_or_float
{
int int_member;
float float_member;
};
struct node
{
union int_or_float data;
struct node *next;
};
我想写这样的东西:
typedef struct node item;
但是如何指定我喜欢 item 的 union 类型呢?
最佳答案
你不知道。 union 的根本在于它可以是您放入其中的任何数据。
如果您写入 int_member
,那么它将保存一个 int。
如果您写入 float_member
,它将包含一个 float 。 (如果您随后从 int_member
中读取,一切都会崩溃。)
关于c - 如何在结构中使用 union ,并为每个结构定义不同的 union 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7407810/