如何初始化嵌套数组

时间:2014-04-10 16:51:38

标签: c

初始化以下2级嵌套数组的正确语法是什么?

z3 src # cat tc.c
#include <stdio.h>

typedef struct level1_t {
        char                           var[15];
        int                            value;
} level1_t;

typedef struct level2_t {
    level1_t     data[3];
} level2_t;

level2_t level2[1] = {
                [0]={
                        [0]={"one",1},
                        [1]={"two",2},
                        [2]={"three",3}
                }
};

int main() {

        printf("%s\n",level2[0].data[1].var);
}
z3 src # gcc -ggdb -o tc tc.c
tc.c:14:4: error: array index in non-array initializer
tc.c:14:4: error: (near initialization for 'level2[0]')
tc.c:15:4: error: array index in non-array initializer
tc.c:15:4: error: (near initialization for 'level2[0]')
tc.c:15:4: error: extra brace group at end of initializer
tc.c:15:4: error: (near initialization for 'level2[0]')
tc.c:15:4: warning: excess elements in struct initializer
tc.c:15:4: warning: (near initialization for 'level2[0]')
tc.c:16:4: error: array index in non-array initializer
tc.c:16:4: error: (near initialization for 'level2[0]')
tc.c:16:4: error: extra brace group at end of initializer
tc.c:16:4: error: (near initialization for 'level2[0]')
tc.c:16:4: warning: excess elements in struct initializer
tc.c:16:4: warning: (near initialization for 'level2[0]')
z3 src #

2 个答案:

答案 0 :(得分:4)

更改

level2_t level2[1] = {
                [0]={
                        [0]={"one",1},
                        [1]={"two",2},
                        [2]={"three",3}
                }
};

level2_t level2[1] = {
                [0].data = {
                        [0]={"one",1},
                        [1]={"two",2},
                        [2]={"three",3}
                }
};

现在您正尝试将结构初始化为数组,而您需要初始化data字段。

正如你在评论中所提到的,如何在没有索引的情况下做同样的事情:

level2_t level2[] = {
    {
        .data = {
            {"one", 1},
            {"two", 2},
            {"three", 3}
        }
    }
};

答案 1 :(得分:0)

level2_t level2 =
{
   {"one, 1},
   {"two, 2},
   {"three", 3}
};