【问题标题】:union within struct. compilation warnings. c结构内的联合。编译警告。 C
【发布时间】:2014-11-30 20:11:34
【问题描述】:

我有闲置的结构:

struct lshort_sched_param {
    int requested_time;
    int level;
};

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

我正在尝试像这样创建它们的新实例:

struct lshort_sched_param *l = {2 ,1};
struct sched_param *p = {3, l}; 

并得到一些警告:

test.c:5: warning: initialization makes pointer from integer without a cast
test.c:5: warning: excess elements in scalar initializer
test.c:5: warning: (near initialization for `l')
test.c:6: warning: initialization makes pointer from integer without a cast
test.c:6: warning: excess elements in scalar initializer
test.c:6: warning: (near initialization for `p')

谁能帮我弄清楚?

【问题讨论】:

  • 你的代码有各种各样的问题。为什么要声明一个指针并将其初始化为struct
  • 请注意,您在此处声明了一个 anonymous 联合。声明一个标识符来配合它呢?如union { ... } foo;

标签: c struct compiler-warnings unions


【解决方案1】:

这是不允许的:

struct lshort_sched_param *l = {2 ,1};

包含多个元素的大括号括起来的初始化器列表只能初始化struct 或数组,而不是指针。

你可以写:

struct lshort_sched_param m = { 2, 1 };
struct lshort_sched_param *ptr_m = &m;     // optional

您还需要考虑m 的存储时长。 (注意,我使用m 而不是l 作为变量名,因为后者在许多字体中看起来像1)。

另一种可能是:

struct lshort_sched_param *ptr_m = (struct lshort_sched_param) { 2, 1 };

在这种情况下,您可以修改ptr_m 指向的对象。这称为复合文字。如果ptr_m 有,则它具有自动存储持续时间(“在堆栈上”);否则它具有静态存储持续时间。


但是,struct sched_param *p = {3, l}; 的情况会变得更糟。同样,初始化程序无法初始化指针。

另外,联合初始化器只能有一个元素;不允许尝试初始化多个联合成员。无论如何,这没有任何意义。 (也许您误解了工会的工作方式)。

另一个可能的问题是文件范围内的初始化器必须是常量表达式。

【讨论】:

  • 发布更多上下文以获得更好的建议。这是在函数中,还是在全局中?你想对这个工会做什么?
【解决方案2】:

我认为您想要执行以下操作:

struct lshort_sched_param {
    int requested_time;
    int level;
};

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

要为结构/联合分配内存,请执行以下操作:

struct lshort_sched_param l = {2 ,1};
union sched_param p;
// init
// either this
p.sched_priority = 3;
// or that
p.lshort_params = l;

您的struct sched_param *p = {3, l}; 行没有意义。

【讨论】:

    【解决方案3】:

    您正在声明指针,但在您尝试修改它们所指向的东西之前,它们必须指向一些东西,这可以像这样使用 malloc 完成。

    struct lshort_sched_param *l = NULL;
    l = malloc(sizeof(struct lshort_sched_param));
    
    struct sched_param *p = NULL;
    p = malloc(sizeof(struct sched_param));
    

    我们在做什么?好吧,malloc 在内存上分配一些字节并返回一个指向块开头的指针,在我们的例子中,我们将 malloc 返回的指针分配给我们的指针 l 和 p,结果是现在 l 和 p 指向我们刚刚制作的结构。

    那么就可以这样改变p和l所指向的结构体的值了。

    l->requested_time = 2;
    l->level = 1;
    p->sched_priority = 3;
    p->lshort_params.requested_time = 1;
    p->lshort_params.level = 1;
    

    编辑:

    显然,您也可以这样做。

    struct lshort_sched_param p = {2, 1};
    

    然后。

    struct lshort_sched_param *ptr = &p;
    

    但是当你在做的时候。

    struct lshort_sched_param *l;
    

    您只是声明了一个指针,仅此而已,在您向他分配变量的地址之前,它不会指向任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      相关资源
      最近更新 更多