Static struct initialization in C

廉价感情. 提交于 2020-01-01 01:15:39

问题


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?


回答1:


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.




回答2:


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. So your current code attempts using the static keyword 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:

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.




回答3:


#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



来源:https://stackoverflow.com/questions/7691187/static-struct-initialization-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!