R
Rennie deGraaf
A question regarding this code, which defines a struct containing a size
and a variable-sized array:
typedef struct
{
uint16_t count;
unsigned char bytes[];
} foo_t;
....
foo_t* foo = (foo_t*)malloc(100 + sizeof(foo_t));
GCC 3.3.2 accepts this, and returns '2' as the result of
'sizeof(foo_t)'. I realize that the size of any struct is
machine/compiler dependent, but can I reasonably expect this code to be
portable? My reading of K&R implies that an array with no size is an
incomplete type, and that you can't take the size of an incomplete type,
and also that structs can't contain objects of incomplete types.
However, I couldn't find anything in the GCC documentation stating that
this was one of their extensions.
If this is not portable, then what is the best way to define a portable
variable-sized array with a header in a contiguous block of memory?
Would I need to just malloc an array, cast the header bytes
appropriately when necessary, and offset everything?
Rennie
and a variable-sized array:
typedef struct
{
uint16_t count;
unsigned char bytes[];
} foo_t;
....
foo_t* foo = (foo_t*)malloc(100 + sizeof(foo_t));
GCC 3.3.2 accepts this, and returns '2' as the result of
'sizeof(foo_t)'. I realize that the size of any struct is
machine/compiler dependent, but can I reasonably expect this code to be
portable? My reading of K&R implies that an array with no size is an
incomplete type, and that you can't take the size of an incomplete type,
and also that structs can't contain objects of incomplete types.
However, I couldn't find anything in the GCC documentation stating that
this was one of their extensions.
If this is not portable, then what is the best way to define a portable
variable-sized array with a header in a contiguous block of memory?
Would I need to just malloc an array, cast the header bytes
appropriately when necessary, and offset everything?
Rennie