Инициализация вложенной структурной переменной

Как я могу инициализировать эту вложенную структуру в 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 ? */ };

person Stick it to THE MAN    schedule 19.11.2009    source источник
comment
должно быть char s[16];, а не char[16] s;   -  person Kcats    schedule 19.11.2009
comment
Аналогичный пост здесь посвящен SO для C ++.   -  person tranmq    schedule 19.11.2009


Ответы (4)


Чтобы инициализировать все до 0 (правильного типа)

StructOuter myvar = {0};

Чтобы инициализировать элементы определенным значением

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

Изменить

Если у вас есть компилятор C99, вы также можете использовать «назначенные инициализаторы», например:

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) */
person pmg    schedule 19.11.2009
comment
Чтобы уточнить, StructOuter myvar = { 0 }; будет делать то же самое (0-инициализацию) для всех внутренних структур, поэтому нам не нужно явно устанавливать для них {0, NULL}, верно? - person domsson; 28.04.2020
comment
Да, @domsson, инициализатор { 0 } все инициализирует 0, при необходимости рекурсивно. - person pmg; 28.04.2020

В частности, чтобы выделить структурные метки:

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 */
};
person Willem    schedule 14.12.2017

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" };

Кажется, что a и b не могут быть инициализированы на месте в простом C

person Kcats    schedule 19.11.2009

Следующее также работает с GCC, C99. GCC на это не жалуется. Я не уверен, что это стандартно.

double arr[] = { 1.0, 2.0 };   // should be static or global
StructOuter myvar = 
{
    .f = 42,
    .s = "foo",
    .a.size = 2,
    .a.elems = &arr,
    .b.size = 0,  // you can explicitly show that it is zero
    // missing members will actually be initialized to zero
};
person uffu    schedule 11.09.2020