C语言 C中的静态结构初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7691187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:51:15  来源:igfitidea点击:

Static struct initialization in C

cstructinitialization

提问by Peretz

I have a structtype as shown below:

我有一个结构类型,如下所示:

typedef struct position{
    float X;
    float Y;
    float Z;
    float A;
} position;

typedef struct move{
    position initial_position;
    double feedrate;
    long speed;
    int g_code;
} move;

I am trying to staticallyinitialize it, but I have not found a way to do it. Is this possible?

我正在尝试静态初始化它,但我还没有找到一种方法来做到这一点。这可能吗?

回答by Kerrek SB

It should work like this:

它应该像这样工作:

move x = { { 1, 2, 3, 4}, 5.8, 1000, 21 };

The brace initializers for structs and arrays can be nested.

结构体和数组的大括号初始值设定项可以嵌套。

回答by Jason

C doesn't have a notion of a static-member object of a struct/class like C++ ... in C, the statickeyword on declarations of structures and functions is simply used for defining that object to be only visible to the current code module during compilation. So your current code attempts using the statickeyword won't work. Additionally you can't initialize structure data-elements at the point of declaration like you've done. Instead, you could do the following using designated initializers:

C 没有像 C++ 这样的结构/类的静态成员对象的概念......在 C 中,static结构和函数声明上的关键字仅用于定义该对象仅对当前代码模块可见在编译过程中。因此,您当前使用static关键字的代码尝试将不起作用。此外,您无法像您所做的那样在声明点初始化结构数据元素。相反,您可以使用指定的初始值设定项执行以下操作:

static struct {
    position initial_position;
    double feedrate;
    long speed;
    int g_code;
} move = { .initial_position.X = 1.2,
           .initial_position.Y = 1.3,
           .initial_position.Z = 2.4,
           .initial_position.A = 5.6,
           .feedrate = 3.4, 
           .speed = 12, 
           .g_code = 100};

Of course initializing an anonymous structure like this would not allow you to create more than one version of the structure type without specifically typing another version, but if that's all you were wanting, then it should do the job.

当然,初始化这样的匿名结构将不允许您创建多个版本的结构类型,而无需专门键入另一个版本,但如果这就是您想要的,那么它应该可以完成这项工作。

回答by akappa

#include <stdio.h>

struct A {
    int a;
    int b;
};

struct B {
    struct A a;
    int b;
};

static struct B a = {{5,3}, 2};

int main(int argc, char **argv) {
    printf("A.a: %d\n", a.a.a);
    return 0;
}

result:

结果:

$ ./test

A.a: 5

$ ./测试

AA:5