A structure with a flexible member of an array is apparently not intended to be declared, but is used in combination with a pointer to this structure. When declaring an element of a flexible array, there must be at least one other member, and the flexible member of the array must be the last member of this structure.
Say I have one that looks like this:
struct example{ int n; int flm[]; }
Then, to use it, I will have to declare a pointer and use malloc to reserve memory for the contents of the structure.
struct example *ptr = malloc(sizeof(struct example) + 5*sizeof(int));
That is, if I want my flm [] array to contain five integers. Then I can just use my structure for example:
ptr->flm[0] = 1;
My question is: shouldn't I just use a pointer instead? This is not only compatible with pre-C99, but I could use it with or without a pointer to this structure. Given that I should already use malloc with flm, shouldn't I just do this?
Consider this new definition of an example struct;
struct example{ int n; int *notflm; } struct example test = {4, malloc(sizeof(int) * 5)};
I would even use a replacement in the same way as a flexible array element:
Will this work? (Subject to the above definition of an example with notflm)
struct example test; test.n = 4; notflm = malloc(sizeof(int) * 5);
c struct flexible-array-member
Theo Chronic Aug 01 '13 at 18:25 2013-08-01 18:25
source share