c - 匿名结构

标签 c gcc struct c11

我需要一个嵌入到结构测试中的匿名结构,这样它的设置如下:

#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 } };

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

我希望这能澄清!

最佳答案

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

文档的相关摘录:

Unless -fms-extensions is used, the unnamed field must be a structure or union definition without a tag (for example, ‘struct { int a; };’). If -fms-extensions is used, the field may also be a definition with a tag such as ‘struct foo { int a; };’, a reference to a previously defined structure or union such as ‘struct foo;’, or a reference to a typedef name for a previously defined structure or union type.

引用:this page获取更多信息。

关于c - 匿名结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25217505/

相关文章:

c - 动态和静态字符数组

c - 结构填充和包装

c - 如何手动加载和执行 ELF 二进制可执行文件?

c++ - 数据结构对齐

arrays - 检查结构字符串数组是否包含另一个字符串数组的元素

c - strcmp 总是返回 1

c++ - 使用 gcc 编译 .cpp

C:将预编译代码编译为内联

c++ - 传递成员为 vector 的结构

c - 范围前向声明