Discussion:
Initialization of nested flexible array members
Alexandre Courbot
2003-10-07 14:32:54 UTC
Permalink
Hello everybody,

Since a few versions, it appears that gcc doesn't allow anymore the
initialization of flexible array members. The following code did compile
under 2.95 but doesn't under 3.3.1:

typedef struct
{
char a;
char b;
int flexo[];
} EnclosedStruct;

typedef struct
{
int a;
int b;
EnclosedStruct s;
} MyStruct;

int main(int argc, char * argv[])
{
MyStruct toto = { 10, 20, { 'a', 'b', { 0, 1, 2, 3 } } };

}

$ gcc test.c -o test
test.c: In function `main':
test.c:17: error: initialization of flexible array member in a nested context
test.c:17: error: (near initialization for `toto.s.flexo')
test.c:17: error: non-static initialization of a flexible array member
test.c:17: error: (near initialization for `toto.s')

This is however something we *really* need to do, and consider safe since the
flexible member is located at the end of the enclosing structure. Is there
any workaround we could use, or do anybody have any advice to give to face
this situation?

Thanks in advance,
Alex.
Eljay Love-Jensen
2003-10-07 15:05:03 UTC
Permalink
Hi Alexandre,

Declare your stretchy-buffered struct this way:

typedef struct
{
char a;
char b;
int flexo[1024];
} EnclosedStruct;

Instead of "1024", use whatever largest possible size the struct could conceivably need to accommodate.

HTH,
--Eljay
Alexandre Courbot
2003-10-07 15:18:39 UTC
Permalink
Post by Alexandre Courbot
typedef struct
{
char a;
char b;
int flexo[1024];
} EnclosedStruct;
Instead of "1024", use whatever largest possible size the struct could
conceivably need to accommodate.
This is unfortunately not an option, since the code is designed to run on
constraint embedded targets with 1K RAM at best... :)

Alex.
Burak Serdar
2003-10-07 16:09:23 UTC
Permalink
This post might be inappropriate. Click to display it.
Eljay Love-Jensen
2003-10-07 15:53:59 UTC
Permalink
Hi Alexandre,

You could try this:

#define DECLARE_MY_STRUCT(len) \
typedef struct { \
char a; \
char b; \
int flexo[len]; \
} EnclosedStruct_##len; \
typedef struct { \
int a; \
int b; \
EnclosedStruct s; \
} MyStruct_##len;

DECLARE_MY_STRUCT(3);

int main(int argc, char * argv[])
{
MyStruct_3 toto = { 10, 20, { 'a', 'b', { 0, 1, 2, 3 } } };
}

If you need to pass a MyStruct_3 to a routine taking a MyStruct*, you can cast it to a MyStruct.

HTH,
--Eljay
Loading...