A struct with a flexible array member, apparently, is not intended to be declared, but rather used in conjunction with a pointer to that struct. When declaring a flexible array member, there must be at least one other member, and the flexible array member must be the last member in that struct.
Let's say I have one that looks like this:
struct example{
int n;
int flm[];
}
Then to use it, I'll have to declare a pointer and use malloc to reserve memory for the structure's contents.
struct example *ptr = malloc(sizeof(struct example) + 5*sizeof(int));
That is, if I want my flm[] array to hold five integers. Then, I can just use my struct like this:
ptr->flm[0] = 1;
My question is, shouldn't I be able to just use a pointer instead of this? Not only would it be compatible pre-C99, but I could use it with or without a pointer to that struct. Considering I already have to use malloc with the flm, shouldn't I just be able to do this?
Consider this new definition of the example struct;
struct example{
int n;
int *notflm;
}
struct example test = {4, malloc(sizeof(int) * 5)};
I'd even be able to use the replacement the same way as the flexible array member:
Would this also work? (Provided the above definition of example with notflm)
struct example test;
test.n = 4;
notflm = malloc(sizeof(int) * 5);
struct
as a way of implementing flexible arrays is not part of the C99 standard (and can have portability problems, mainly due to hidden padding for array/pointer alignment). – Tibiastruct
as a way of implementing flexible arrays would, indeed, be silly. (Using a pointer as the last element of astruct
, and having it point to separately-allocated memory, however, is perfectly reasonable and happens all the time. It's just not the same thing as flexible arrays.) – Signifystruct foo {int bar; int *ary;} *my; my=malloc(sizeof(struct foo)+10*sizeof(int)); my.ary=(int*)(my+1);
, approximately. This is deeply stupid, of course. The other thing is to let the last element of the struct be a pointer to elsewhere, properly initialized with the address of a properly allocated chunk of memory. This does not constitute a struct with flexible array member, it's simply a different technique with its own different set of issues. – Signify