I haven't played around with structs in a while so bear with me. Try this.

Code (C):

typedefstruct my_structure

{

some_field1;

some_field2;

some_field3;

};

my_structure structure_array[50];

structure_array[2]->some_field2 = some_data;

Click to expand...

What he's trying to do is to initialize all of the structures in an array of structs (and in which each element is a struct that contains a struct within it) at the same time that he declares the array itself.

Should be possible and I think the link I provided gives enough info to do it. Personally, I seldom initialize variables at declaration time as I prefer to specifically initialize just those variables that have a specific need to be initialized to specific values. So I would probably write a function to initialize each type of struct. But that's a personal preference and the propriety of this approach can be argued both pro and con.

First, if you only want to declare the array and not initialize it, then just declare it:

table_t aTables[2];

With nested structs like this, there are easier to read ways to initialize it than when you declare it, but if you must (this is really ugly, don't ever do this in real code) the following compiles and initializes all your elements. Use the variable and memory watch tools in your debugger to see where these values end up.

Technically it works, but it's not a good idea. It makes for delicate code. If one of the structs changes, your initialization will be broken, and it might not be obvious. Say you're initializing dir[1].state[2] to a specific value using the code above. Some time from now, maybe a co-worker or maybe yourself comes along and decides to add an extra element inside struct abc, maybe they add another int:

typedef struct
{
uint32_t more_states[2];
uint16_t states[4];
}abc;

Now your initialization is broken, the wrong values will go in the wrong fields and you might not notice until it causes problems. IMHO, it's much better to initialize the fields explicitly. It's easier to read and makes for more durable code.

While we're on the topic; it's also possible to use memcpy, fread, etc.. to directly initialize fields, but this too can be problematic. Depending on the platform, your compiler settings, etc.. things like padding can change and you can end up with a bad result. IMHO it's almost always better to access fields directly by name, unless you have a very specific reason to access by address instead.

I dont use structs that much anymore either but this looks like a problem that would better be solved with a multidimensional array. I dont really know how the data has to be accessed though in the actual application after all the initialization is over with.