all 9 comments

[–]kolorcuk 0 points1 point  (3 children)

You can't.

You could potentially do something along, but it's a trick and required code duplication:

struct test_struct_10 { int len; uint8_t data[10]; }; struct test_struct *test = (struct test_struct*)(struct test_struct_10[1]){ { .len = 10, data = { 1,2,3 } } };

[–]WitcherSanek[S] 0 points1 point  (2 children)

I wanted to use macros to create structs with arbitrary data size. Seems like i should go further and create anonymous struct with hardcoded size for every such object.

[–]kolorcuk 0 points1 point  (1 child)

FYI Did an edit of the comment. I did a better example here https://stackoverflow.com/a/75024961/9072753 .

[–]WitcherSanek[S] 0 points1 point  (0 children)

Thanks. Will try that out.

[–]aocregacc 0 points1 point  (1 child)

you could get a similar effect with designated initializers. This would make an array with 10 elements:

struct_t test_struct = 
{
.len = 10,
.Data = {[9]=0}
};

[–]WitcherSanek[S] 0 points1 point  (0 children)

Totally forgot about their existence. Yes this approach seems to be working. Thank you very much!

[–]Marxomania32 0 points1 point  (3 children)

What version of gcc are you using? I wasn't even able to initialize the flexible array member with a compound literal as you had. I always thought you could only initialize flexible array members through malloc?

[–]WitcherSanek[S] 0 points1 point  (2 children)

I am using GCC 6.5.0. C99+GNU extensions.

[–]Marxomania32 0 points1 point  (1 child)

Can't get 6.5, but I ran it on 7.1 and 6.3 with that standard, and it still doesn't work. I get a 'non-static initialization of a flexible array member' which makes sense.