I’m quite confusing how to efficiently manage (populating and accessing) the following data structure in C. To describe in brief, I have a struct that contains a member of another struct, and that struct has a member of another different struct and so forth. Something like this:
typedef struct
{
int num;
} D;
typedef struct
{
D *boo;
} C;
typedef struct
{
C *far;
} B;
typedef struct
{
int foo;
B *bar;
} A;
A *func() {
A *var;
// POPULATE var
}
int main(...) {
A *a = func();
// PRINTING
}
So, which way is the best way to manage this data structure? I mean how am I going to populate the data for this A-typed pointer?
Imagine that I’m about to print all the data that a keeps (at // PRINTING), I guess I’m gonna have something like: a->bar->far->boo->num. I don’t know whether this properly works and thus, is robust.
This wouldn’t be any easier in e.g. Python, if you’re selecting such a scattered design then it’s going to be a bit painful to manage, naturally.
The printing would work just as you say, C’s
->operator is typically used just like that. Of course, if there can be NULL pointers where the structure is not “complete” you need to check for that before dereferencing the pointer, or you will have undefined behavior.Population would probably be best done by writing functions to create an instance at each layer, which can then call each other in a chain to set up the top-most type:
This is a bit cumbersome since all the actual data (
fooandnum) must be passed in to the top-level function that creates an instance ofA, but it works and is very straight-forward.Notice how we catch errors from the lower-level memory allocators, by making sure the
Bpointer is non-NULL. These kinds of checks would be necessary in the othercreate-functions, too.