简体   繁体   English

C中的静态结构初始化

[英]Static struct initialization in C

I have a struct type 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 statically initialize it, but I have not found a way to do it. 我试图静态初始化它,但我还没有找到办法。 Is this possible? 这可能吗?

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. 结构和数组的大括号初始值设定项可以嵌套。

C doesn't have a notion of a static-member object of a struct/class like C++ ... in C, the static keyword on declarations of structures and functions is simply used for defining that object to be only visible to the current code module during compilation. C没有像C ++那样的结构/类的静态成员对象的概念...在C中,结构和函数声明的static关键字仅用于定义该对象仅对当前代码可见编译期间的模块。 So your current code attempts using the static keyword won't work. 因此,使用static关键字的当前代码尝试将不起作用。 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 : 相反,您可以使用指定的初始值设定项执行以下操作:

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. 当然,初始化这样的匿名结构不会允许您创建多个版本的结构类型而无需专门键入其他版本,但如果这是您想要的全部,那么它应该完成这项工作。

#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 $ ./test

Aa: 5 Aa:5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM