[英]Initialize array of structures
I am having trouble initializing an array of structures in C. Here is my structure : 我在C中初始化结构数组时遇到问题。这是我的结构:
typedef struct Voie {
int num;
int sem_num[3];
int crois[3];
} Voie;
The two arrays will contain 0, 2 or 3 integers. 这两个数组将包含0,2或3个整数。
I have an array of 12 "Voie" : 我有一个12“Voie”阵列:
Voie voies[12];
And I want each of these to be initialized with these parameters : 我希望用这些参数初始化每个参数:
{1,{0,16,1},{4,7,8}}
{2,{2,3},{4,5}}
{3,{},{}}
{4,{4,17,5},{7,10,11}}
{5,{6,7},{7,8}}
{6,{},{}}
{7,{8,17,9},{10,1,2}}
{8,{10,11},{10,11}}
{9,{},{}}
{10,{12,16,13},{1,4,5}}
{11,{14,15},{1,2}}
{12,{},{}}
I have tried with a function returning a structure, separating each case with a switch, but got redefinition issues. 我试过一个函数返回一个结构,用一个开关分隔每个案例,但有重新定义的问题。 Then I found what I assume to be the best solution but still can't make it run :
然后我发现我认为是最好的解决方案,但仍然无法运行:
int cas[][] = { {1,{0,16,1},{4,7,8}},
{2,{2,3},{4,5}},
{3,{},{}},
{4,{4,17,5},{7,10,11}},
{5,{6,7},{7,8}},
{6,{},{}},
{7,{8,17,9},{10,1,2}},
{8,{10,11},{10,11}},
{9,{},{}},
{10,{12,16,13},{1,4,5}},
{11,{14,15},{1,2}},
{12,{},{}} };
for (i=0 ; i<12 ; i++) {
voies[i] = cas[i];
}
I'm not even sure that this is possible, since the following works : 我甚至不确定这是可能的,因为以下工作:
Voie v = {1,{0,16,1},{4,7,8}};
But not the following : 但不是以下内容:
int tab[] = {1,{0,16,1},{4,7,8}};
Voie v = tab;
Also : how can I access to each of the elements in my structure once it is initialized ? 另外:初始化后,如何访问结构中的每个元素?
Thank you for your help. 谢谢您的帮助。
You can simply initialize your array with: 您可以使用以下命令初始化数组:
EDITED: 编辑:
Voie voies[12] = {
{1,{0,16,1},{4,7,8}},
{2,{2,3,},{4,5,}},
{3,{0,},{0,}},
{4,{4,17,5},{7,10,11}},
{5,{6,7,},{7,8,}},
{6,{0,},{0,}},
{7,{8,17,9},{10,1,2}},
{8,{10,11,},{10,11,}},
{9,{0,},{0,}},
{10,{12,16,13},{1,4,5}},
{11,{14,15,},{1,2,}},
{12,{0,},{0,}}
};
You can access the elements like voies[5].sem_num[0]. 您可以访问voies [5] .sem_num [0]等元素。
If Im not wrong, the example value above would be 17. 如果我没错,上面的示例值将是17。
Neither your declaration cas[][]
nor your initialization with empty {}
is standard C. 您的声明
cas[][]
和使用空{}
初始化都不是标准C.
You may have at most one empty []
in a declaration, and you'd have to put at least one 0
inside the {}
. 您可能在声明中最多只有一个空
[]
,并且您必须在{}
内放置至少一个0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.