user1225606
user1225606

Reputation: 1153

Initializing structure array inside a structure array

I have a question in initializing my structure array inside a structure array. for example if I have a code as below:

#include <stdio.h>

int main() {

typedef struct {
    int a;
    int b;
    int c;
} FIRST_T;

typedef struct {
    int x;
    int y;
    int z;
    FIRST_T *p;
} SECOND_T;

FIRST_T p1[]={{1,2,3},{3,4,5},{6,7,8}};
FIRST_T p2[]={{4,5,6},{7,8,9}};

SECOND_T my_second[]=
{
{1,2,3,p1},
{4,5,6,p2}
};

}

if I have to initialize my first array in second array intialization part itself, then how would I write my typedef of SECOND_T? like

SECOND_T my_second[]=
{
{1,2,3,{{1,2,3},{4,5,6},{7,8,9}}},
{4,5,6,{{1,1,1},{2,2,2}}}
};

then how should be my SECOND_T?

I am sure I can't define it as:

typedef struct {
    int x;
    int y;
    int z;
    FIRST_T p[]; //(I know its a blunder)
} SECOND_T;

Please help.

Upvotes: 0

Views: 1535

Answers (4)

Jinghao Shi
Jinghao Shi

Reputation: 1087

I don't think you can do this, i.e, initialize the FIRST_T inside the initialization of SECOND_T, other than the first way you do it. Think about it, how can the compiler tell how many FIRST_T are there in SECOND_T? The problem here is, you can NOT define an array of flexible size struct statically.

Upvotes: 1

Jens Gustedt
Jens Gustedt

Reputation: 78903

I don't know if I completely capture the question that you have. If it is that you want to avoid to have to declare an auxiliary variable for the pointers in the structure you can use a compound literal as follows:

SECOND_T my_second[] = {
  {1,2,3, &(FIRST_T){{1,2,3},{3,4,5},{6,7,8}}},
  {4,5,6, &(FIRST_T){{4,5,6},{7,8,9}}}
};

You'd have a compiler that complies to C99 for that.

Upvotes: 0

laifjei
laifjei

Reputation: 646

you can't to do like that:

SECOND_T my_second[]=
{
{1,2,3,{{1,2,3},{4,5,6},{7,8,9}}},
{4,5,6,{{1,1,1},{2,2,2}}}
};

with

typedef struct {
int x;
int y;
int z;
FIRST_T p[]; //(I know its a blunder)

} SECOND_T;

becase the compiler don't know how to malloc memory for this struct. if you must do like this, you should define

typedef struct { int x,y,z; FIRST_T p[CONST_VALUE];}SECOND_T;

but I advise you use the first style that you write.

Upvotes: 0

littleadv
littleadv

Reputation: 20262

You can't define a type with unbounded array in C, you have to specify the dimension. So you either do:

typedef strut {
    int x;
    int y;
    int z;
    FIRST_T f[SOME_VALUE];
} SECOND_T;

and then initialize SOME_VALUE count of members always, or do it the way you did.

Upvotes: 1

Related Questions