I have a struct type as shown below:
typedef struct position{
float X;
float Y;
float Z;
float A;
} posi开发者_StackOverflowtion;
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. 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.
#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
精彩评论