Inizializzazione della variabile struct annidata

Inizializzazione della variabile struct annidata

Per inizializzare tutto a 0 (del tipo giusto)

StructOuter myvar = {0};

Per inizializzare i membri su un valore specifico

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} */

Modifica

Se hai un compilatore C99, puoi anche usare "inizializzatori designati", come 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) */

Per evidenziare in particolare le etichette delle strutture:

StructInner a = {
    .size: 1,
    .elems: { 1.0, 2.0 }, /* optional comma */
};

StructOuter b = {
    .a = a, /* struct labels start with a dot */
    .b = a,
         a, /* they are optional and you can mix-and-match */
         a,
    .e = {  /* nested struct initialization */
        .size: 1,
        .elems: a.elems
    },
    .f = 1.0,
    .s = "Hello", /* optional comma */
};

double a[] = { 1.0, 2.0 };
double b[] = { 1.0, 2.0, 3.0 };
StructOuter myvar = { { 2, a }, { 3, b }, { 2, a }, { 3, b }, { 2, a }, 1, "a" };

Sembra che aeb non possano essere inizializzati sul posto in C

normale