Select to view content in your preferred language

In C, going to create a new long nested structures

349
0
01-30-2023 06:32 AM
hectorsalamanca
Deactivated User

What is the best/cleanest approach to start (in a local function) a lengthy chain of nested structures where each structure just holds pointers to other structures, as seen below:

typedef struct A{
struct B{
    struct C *c /* OPTIONAL */;
    struct D *d /* OPTIONAL */;
    struct E *e /* OPTIONAL */;
    struct F *f /* OPTIONAL */;
} *b;
struct G{
    struct F *f /* OPTIONAL */;
    struct D *d /* OPTIONAL */;
    struct H *h /* OPTIONAL */;
    struct F *f /* OPTIONAL */;
} *g;
    } a;

 

Each of the references to the nested structures link to structures that contain pointers to other nested structures (I know, it's weird!)

I believe I need to define a tmp pointer for each struct member and allocate memory for it, as well as a tmp struct variable and point the former to the latter:

B *b_ptr = CALLOC(1,sizeof(b_ptr));
B b_tmp;
b_ptr = &b_tmp;
b_tmp.itsMember1 = CALLOC(1,sizeof(itsMember1));
TypeOfItsMember1 itsMember1_tmp;
..
..

This will necessitate a plethora of local variables and excruciatingly repetitious code. Is there a better method to thoroughly initialise the parent struct? 

0 Kudos
0 Replies