Initializing structure array inside a structure array

ぃ、小莉子 提交于 2019-12-13 07:15:46

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/9834897/initializing-structure-array-inside-a-structure-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!