Reputation: 1891
I have this structure
typedef struct {
int Length;
int Data[];
} MyStruct;
And this macro to initialize the struct
#define FillStruct(...) { .Length = sizeof((int[]){__VA_ARGS__}), .Data = {__VA_ARGS__} }
So I can initialize the struct with
MyStruct Obj = FillStruct(1, 2, 3, 4, 5);
But this doesn´t work. I got this error:
non-static initialization of a flexible array member
I can compile the code when I change Obj
into a static
initialization
static MyStruct Obj = FillStruct(1, 2, 3, 4, 5);
but now the debugger gives me some weird informations about this object.
So how can I solve this problem? I´m looking for a solution to intialize this struct during compile time on an embedded device (AVR MCU). In this case I can´t use solutions with malloc
etc. And the data in this struct is constant and got stored in the program memory. So the application only reads this data.
Upvotes: 0
Views: 310
Reputation: 1891
I found one solution. The compiler throw this error, because I declared and initialize the structure inside of main
. Moving this segment out of main
will solve this problem.
The final solution looks like this:
#define VA_NARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) 2 * N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define FillStruct(...) { .Length = VA_NARGS(__VA_ARGS__), .Data = {__VA_ARGS__} }
const MyStruct Obj = FillStruct(1, 2, 3, 4, 5);
int main(void)
{
int B = Obj.Data[2];
// B = 3
}
So everything is fine now. It seems that the wrong debugger output also appears with const
keyword. But now I can remove const
and static
to get the corrent Length
(but not Data
) in the structure.
Upvotes: 1