2009-11-19 4 views
4

Comment puis-je initialiser cette structure imbriquée dans C?Initialisation de la variable struct imbriquée

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 ? */ }; 
+5

devrait être 'char s [16];', pas 'char [16] s;' – Kcats

+0

Il y a un message similaire [ici] (http://stackoverflow.com/questions/629433/how-to-initialize-nested-structures -in-c) sur SO pour C++. – tranmq

Répondre

13

Pour tout initialiser à 0 (du bon type)

StructOuter myvar = {0}; 

Pour initialiser les membres à une valeur spécifique

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

Modifier

Si vous avez un compilateur C99, vous pouvez également utiliser "initialiseurs désignés", comme dans:

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) */ 
2
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" }; 

Il semble a et b ne peut pas être initialisé en place en C plaine

0

Pour mettre en évidence les étiquettes struct en particulier:

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 */ 
}; 
Questions connexes