【问题标题】:Anonymous structs匿名结构
【发布时间】:2014-08-09 10:15:41
【问题描述】:

我需要一个嵌入到 struct test 中的匿名结构,以便它的设置如下:

#include <stdio.h>

struct test {
    char name[20];

    struct {
        int x;
        int y;
    };
};

int main(void) {
    struct test srs = { "1234567890123456789", 0, 0 };
    printf("%d\n", srs.x); // I can access x property without having to go to go within another struct
    return 0;
}

这样我就可以访问 x 和 y 属性,而不必进入另一个结构。

但是我希望能够使用在其他地方声明的结构定义,如下所示:

struct position {
    int x;
    int y;
}

我无法编辑上述结构!

因此,例如,一些伪代码可能是:

#include <stdio.h>

struct position {
    int x;
    int y;
};

struct test {
    char name[20];

    struct position;
};

int main(void) {
    struct test srs = { "1234567890123456789", 0, 0 };
    printf("%d\n", srs.x); // I can access x property without having to go to go within another struct
    return 0;
}

但是这给出了:

warning: declaration does not declare anything
In function 'main':
error: 'struct test' has no member named 'x'

更新:一些评论者想知道如何初始化这样一个结构,所以我写了一个简单的程序供你试验,确保按照答案使用 -fms-extensions 编译!

#include <stdio.h>

struct position {
    int x;
    int y;
};

struct test {
    char name[20];

    struct position;
};

int main(void) {
    struct test srs = { "1234567890123456789", 1, 2 };
    printf("%d\n", srs.x);
    return 0;
}

输出为 1,这是您所期望的。

不需要:

struct test srs = { "1234567890123456789", { 1, 2 } };

但是,如果你这样做,它会给出相同的输出而没有警告。

我希望这可以澄清!

【问题讨论】:

  • 你不能使用指针强制转换、联合或继承吗?你的问题不是很清楚...
  • 我已经更新了我的问题,希望现在更清楚了。
  • 而不是return 0; 表示成功。
  • 好的;我已经更改了返回值,即使它不相关。
  • @CHRIS 我不明白。如果您使用1, 2, 3, 4 更改零,您提供的第一个代码的输出是什么?它仍然应该是零。如果那是你已经追求的,那很好。但是,如果您希望为x 设置一个初始值,那么您有很多解决方案,其中之一是... = {{set_of_values_for_name}, {value_for_x, value_for_y}};

标签: c gcc struct c11


【解决方案1】:

根据 c11 标准,可以在 gcc 中使用匿名结构。使用-fms-extensions 编译器选项将允许您想要的匿名结构功能。

文档的相关摘录:

除非使用-fms-extensions,否则未命名字段必须是结构体 或没有标签的联合定义(例如,'struct { int a; };')。 如果使用 -fms-extensions,该字段也可以是一个定义 标签,例如'struct foo { int a; };',对先前的引用 已定义的结构或联合,例如“struct foo;”,或对 typedef 先前定义的结构或联合类型的名称。

更多信息请参考:this page

【讨论】:

    【解决方案2】:
    #define position {int x; int y;}
    
    struct test {
        char name[20];
    
        struct position;
    };
    

    扩展为:

    struct test {
        char name[20];
    
        struct {int x; int y;};
    };
    

    【讨论】:

    • 不幸的是,该结构不是我的定义,它来自一个库,所以我无法更改它的定义。
    猜你喜欢
    • 2014-01-14
    • 2013-04-18
    • 2020-10-28
    • 2016-09-03
    • 2019-11-17
    • 2018-03-28
    • 2015-02-23
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多