【问题标题】:Struct with union: structure has no member named [duplicate]带有联合的结构:结构没有名为[重复]的成员
【发布时间】:2015-01-30 01:14:07
【问题描述】:

我有以下结构:

struct sched_param {
    union {
        int sched_priority;
        struct lshort_sched_param lshort_params;
    };
};

struct lshort_sched_param {
    int requested_time;
    int level;
};

每当我创建sched_param param1 结构并尝试更新param1.sched_priority 字段时,我都会收到主题中写入的消息。

struct sched_param param1;
param1.sched_priority = 1;

但是,每当我创建 sched_param param2 并尝试更新 param2.lshort_params.level 时,它都可以正常工作。

struct sched_param param2;
param2.lshort_params.level= 1;

可能是什么原因?

【问题讨论】:

  • 你需要给联合一个标识符,所以它可以被引用。
  • 这是在家庭作业中给我们的结构,所以我不能给工会起个名字。还有其他解决办法吗?

标签: c linux linux-kernel


【解决方案1】:

这是因为你使用的gcc编译器版本不支持unnamed union。看到这个堆栈溢出link

【讨论】:

    【解决方案2】:

    你的工会应该有一个名字,例如

    struct sched_param {
        union {
            int sched_priority;
            struct lshort_sched_param lshort_params;
        } union_member_name;
    };
    

    然后你可以使用param1.union_member_name.sched_priority

    【讨论】:

    • 这是在家庭作业中给我们的结构,所以我不能给工会起个名字。还有其他解决办法吗?
    • @helloV 已经给你解决方案了。
    猜你喜欢
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-11
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多