I want to convert this Python code:
outsides = [
{ 'baz': 7,
'foobar': [ {'bar': 2, 'foo': 1},
{'bar': 4, 'foo': 3},
{'bar': 6, 'foo': 5}]},
{'baz': 8}]
to C. I came up so far with this code:
#include <stdio.h>
struct Inside {
int foo;
int bar;
};
struct Outside {
int baz;
const struct Inside* foobar;
};
const struct Inside insides[] = {
{ .foo = 1, .bar = 2 },
{ .foo = 3, .bar = 4 },
{ .foo = 5, .bar = 6 },
};
const struct Outside outsides[] = {
{ .baz = 7, .foobar = insides },
{ .baz = 8, .foobar = NULL },
};
int main(int argc, char *argv[])
{
printf("outsides: %i\n", sizeof(outsides) / sizeof(Outside));
printf("insides: %i\n", sizeof(outsides[0].foobar));
return 0;
}
But there are two problems:
- How do I inline the insides declaration in the outsides declaration?
- How can I determine the number of inside elements of the foobar member?
For question 2 I could implement some workarounds, like initializing the last element all with 0 and then looping over it and testing for all 0, or adding an additional count member in the Outside struct, but this doesn't look right. It would be perfect, if there could be another indirection: if the foobar member is an array of pointers to Inside elements, then I could just add a null pointer at the end.
Note: this is a simplified example which demonstrates the basic two questions I have, but I can't use a flexible array member, because there is more than one flexible array member in the Outside struct. And of course, the number of objects of the foobar member can vary. And I need a solution which works with C, not C++.