How can I initialize a structure if one field in the structure is itself a structure?
Structure members can be initialized using curly braces '{}'. For example, following is a valid initialization.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
When initializing a struct, the first initializer in the list initializes the first declared member (unless a designator is specified) (since C99), and all subsequent initializers without designators (since C99)initialize the struct members declared after the one initialized by the previous expression.
It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct . Show activity on this post. It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name.
You need to use more braces (actually, they're optional, but GCC makes a warning these days). Here's an example:
struct s1 { int a; int b; };
struct s2 { int c; struct s1 s; };
struct s2 my_s2 = { 5, { 6, 3 } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With