Reputation: 770
I am having trouble initializing an array of structures in C. Here is my structure :
typedef struct Voie {
int num;
int sem_num[3];
int crois[3];
} Voie;
The two arrays will contain 0, 2 or 3 integers.
I have an array of 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.
Upvotes: 2
Views: 193
Reputation: 7472
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,}}
};
Upvotes: 6
Reputation: 78903
Neither your declaration cas[][]
nor your initialization with empty {}
is standard C.
You may have at most one empty []
in a declaration, and you'd have to put at least one 0
inside the {}
.
Upvotes: 2
Reputation: 49
You can access the elements like voies[5].sem_num[0].
If Im not wrong, the example value above would be 17.
Upvotes: 2