- How will I dynamically allocate an array of
struct Registerwith each register having a dynamically allocated array ofstruct Field? - How will I access each of these members (Can I use
Register_A.FieldArray[23].High?)? -
How will I initialize register structure efficiently(assuming that register struct array is a big one) ? (Like a data segment without spending any compute)
struct Field { char High; char Low; char Attribute; }; struct Register { unsigned int ResetValue; struct Field FieldArray[]; };
How will I dynamically allocate an array of struct Register with each register having
Share
I strongly discourage you from using a flex array, because they’re nothing but a kludge. You should instead declare and use it as a
struct Field *,mallocing it to size like any other dynamic array.That said, to
mallocwith an array size ofn_elem:To access the elements:
For initialization: in gcc, at least, you can initialize the array part statically like any other static array. I’m not sure how other compilers handle it.
Why flex arrays are discouraged:
I’ll link this post, but I don’t think the answer is complete (most of the discouragement is because it’s c-99 only), so I’ll add my thoughts.
They are an exception. In essence, you’re declaring the array to be of zero size and accessing it out of bounds every time, just to an extent you have allocated for. You can’t use a struct with a flexible array just like any other struct, e.g. you can’t take the
sizeofthe flexible array. If you declare a static one or an array of them, you can’t use the array member because there’s no space allocated for it.Example of using them in an array:
Output:
They are at the same address. If you try to write to the array member, you overwrite the next object. If you try to read from it, you read data from the next object. Depending on padding, this could even be a nonsense value from the padding.
They’re like
gotostatements, both are potentially useful but more often a bad idea. If you don’t know why they’re dangerous, you shouldn’t be using them (in real code; it’s not a bad idea to play around with them in a test program to see how to use them correctly and how they can introduce problems).