0

I would like to compose a structure that possesses a contiguous array of  flexible members that are, in turn, aggregation of few data fields. With that code pattern I want to: a) store multiple relevant data fields, b) have an array of such instances and c) destroy them all as simply as free(). The code bellow seems do the job:


struct s_symm_root{
       unsigned int size_c;
       struct {
         unsigned int symm_color;
         t_symm_gnrtr symm_gnrtr;
         } _[];
       } *symm_root;
unsigned int SIZE_C = 10;


symm_root = (struct s_symm_root*)malloc( sizeof(struct s_symm_root) + sizeof(*((struct s_symm_root*)NULL)->_) * SIZE_C );

symm_root->size_c = 1;
symm_root->_[0].symm_color = 2;
printf(" %d, %d, %ul.\n", symm_root->size_c, symm_root->_[0].symm_color, sizeof(*((struct s_symm_root*)NULL)->_));

free(symm_root);

My questions is if I can improve it a bit, specially, get rid of that ugly '_' somehow? I thought about anonymous structures but IDK how to implement them...

Thanks for suggestions!

Oleksandr
  • 53
  • 5
  • 1
    [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Jan 31 '20 at 21:00
  • You need to give the array a name, otherwise you can't index it. – Barmar Jan 31 '20 at 21:00
  • But that's not how C works. You can have anonymous structs, but not anonymous arrays. – Barmar Jan 31 '20 at 21:24
  • @Barmar In principle, it could be an extra bracket after the member to address the anonymous structure in array. – Oleksandr Jan 31 '20 at 21:27
  • You mean something like `symm_root->symm_color[0]`? That already has a meaning, which is to treat `symm_color` as an array. It would be very confusing to repurpose it. Anyway, it doesn't exist. – Barmar Jan 31 '20 at 21:30
  • yes, I expected something like that. Just a cozy flavor of multiple arrays as flexible members. – Oleksandr Jan 31 '20 at 21:36
  • This is not specific to flexible array members. There's no shorthand for accessing members of struct arrays. – Barmar Jan 31 '20 at 21:55
  • You can pass around and use the inner array directly, and retrieve the containing structure by deducting its field offset from the pointer cast to `(char*)`. That's a very efficient trick used a lot in malloc implementations and any other situation where you have to _hide_ metadata behind a pointer. –  Feb 01 '20 at 04:01
  • And btw, do NOT prefix the fields with the type of the containing structure (eg. `int symm_foo;`); K&R pre-ANSI C compilers (which used a single namespace for all field structures) went the way of the dodo a long, long, long time ago. And they never supported "flexible" arrays, anyways ;-) –  Feb 01 '20 at 04:04
  • @mosvy you mean something like struct s_symm_root{ unsigned int size_c; char _[]; } *symm_root; ? IDK, as for me, prefixes improve readability of a code. IDE anyway save your time on typing with suggestions. – Oleksandr Feb 01 '20 at 21:43

0 Answers0