Scentle5S
Scentle5S

Reputation: 770

Initialize array of structures

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

Answers (3)

Marian
Marian

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

Jens Gustedt
Jens Gustedt

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

Marcelo Silva
Marcelo Silva

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

Related Questions