Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested struct variable initialization

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 ? */ };
like image 734
Stick it to THE MAN Avatar asked Nov 19 '09 08:11

Stick it to THE MAN


People also ask

How do you initialize a nested structure?

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.

Can you initialize variables in a struct C?

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".

Can you initialize values in a struct?

Structure members cannot be initialized with declaration.

How do you use a struct inside another struct?

One structure can be declared inside another structure in the same way structure members are declared inside a structure. member1; member2; .


1 Answers

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) */
like image 69
pmg Avatar answered Oct 05 '22 16:10

pmg