4 ms·
You can do it without trailing arrays, by stacking the structures after one and other: MyStructA a; MyStructB b; a = malloc((sizeof a) + (sizeof b)); b = (MyS
by quelsolaar 4y ago
You can do it without trailing arrays, by stacking the structures after one and other:
MyStructA a;
MyStructB b;
a = malloc((sizeof a) + (sizeof b));
b = (MyStructB *)&a[1];
You need to make sure that the second struct doesn't have stricter alignment requirements than the one preceding it, but using this technique you can stack any number of structures or arrays of structures in one allocation.
(I would generally not recommend this coding style unless you have very specific requirements of memory usage)
- loeg 4y agoThis is pretty similar to: MyStructA { ... MyStructB b[]; }; MyStructA* a = malloc(sizeof(MyStructA) + sizeof(MyStructB)); b = &a->b[0]; (Except, of course, that the syntax for locating 'b' is nicer this way, because you don't have to explicitly address the memory after 'a' and cast it to 'MyStructB'.)