【问题标题】:Can't set union values无法设置联合值
【发布时间】:2014-12-25 02:20:47
【问题描述】:

我有这个代码

union u_value {
    int i_value;
    long l_value;
    float f_value;
    double d_value;
    char *cp_value;
    int type;
};

union u_value create_int_value(int value) {
    union u_value val;
    val.i_value = value;
    val.type = INT;

    printf("Inside: %d, %d\n", value, val.i_value);

    return val;
}

问题是我无法在 union 中设置值。

例如:

union u_value val = create_int_value(123);
printf("%d\n", val.i_value);

将打印0

我做错了什么?

【问题讨论】:

  • type 本身就是工会的成员。设置它会覆盖您之前设置的任何值。如果您尝试实现标记联合,则需要struct,其中一个成员是联合,另一个单独的成员是类型标记。
  • @TheParamagneticCroissant 我不知道。谢谢!现在感觉好傻
  • 好吧,您不必为此知道任何特别之处。为什么type 字段会很特别?它只是工会的另一个成员。它与所有其他成员共享存储。您需要了解什么是联合...

标签: c unions


【解决方案1】:

您已将 type 成员指定为联合的一部分,这当然会导致其内存与其余字段发生冲突。

要创建"tagged union",您必须将标签与并集分开。比如:

struct u_value {
    int type;
    union {
      int i_value;
      long l_value;
      float f_value;
      double d_value;
      char *cp_value;
    } value;
};

那么你可以使用:

u_value x;
x.type = INT;
x.value.i_value = 4711;

C11你可以将内部union匿名,这很方便。

【讨论】:

  • 大多数编译器也允许漂亮的匿名结构,所以你可以直接访问x.i_value :)
【解决方案2】:

让我猜猜,INT 被定义为 0..?您首先将i_value 设置为123,然后设置type,因为它是一个联合,所以将覆盖i_value

你需要做的是将类型从联合中分离出来

union u_value 
{
    int i_value;
    long l_value;
    float f_value;
    double d_value;
    char *cp_value;
};

struct my_type
{
  union u_value value;
  int type;
};

struct my_type create_int_value(int value) {
    struct my_type val;
    val.value.i_value = value;
    val.type = INT;

    printf("Inside: %d, %d\n", value, val.value.i_value);

    return val;
}

现在类型不会覆盖值。

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-03-19
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-13
    相关资源
    最近更新 更多