How can I initialize this nested struct in C?
typedef struct _s0 {
int size;
double * elems;
}StructInner ;
typedef struct _s1 {
StructInner a, b, c, d, e;
long f;
char[16] s;
}StructOuter; StructOuter myvar = {/* what ? */ };
struct dateOfBirth dob={15,10,1990}; struct studentDetails std={"Mike",21,dob}; Initialize the first structure first, then use structure variable in the initialization statement of main (parent) structure.
An important thing to remember, at the moment you initialize even one object/ variable in the struct, all of its other variables will be initialized to default value. If you don't initialize the values in your struct, all variables will contain "garbage values".
Structure members cannot be initialized with declaration.
One structure can be declared inside another structure in the same way structure members are declared inside a structure. member1; member2; .
To initialize everything to 0 (of the right kind)
StructOuter myvar = {0};
To initialize the members to a specific value
StructOuter myvar = {{0, NULL}, {0, NULL}, {0, NULL},
{0, NULL}, {0, NULL}, 42.0, "foo"};
/* that's {a, b, c, d, e, f, s} */
/* where each of a, b, c, d, e is {size, elems} */
Edit
If you have a C99 compiler, you can also use "designated initializers", as in:
StructOuter myvar = {.c = {1000, NULL}, .f = 42.0, .s = "foo"};
/* c, f, and s initialized to specific values */
/* a, b, d, and e will be initialized to 0 (of the right kind) */
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