Flexible Array Members in C
A flexible array member is an unsized array declared as the last member of a struct to support contiguous variable-length payload allocation.
sizeofreturns the size of the struct excluding the Flexible Array Member. Hence the need to addsize * sizeof(type)in dynamic allocation.- The Flexible Array has to be the last member of the struct.
- The Flexible Array can't be the only member of the struct.
#include <stdlib.h>
struct S {
int size;
int array[];
};
int main(void) {
int size = 5;
struct S* s;
s = malloc(sizeof(struct S) + size * sizeof(int));
return 0;
}
sizeof returns the size of struct S excluding the Flexible Array Member. Hence the need to add size * sizeof(int) in malloc.
The Flexible Array has to be the last member of the struct.
The Flexible Array can't be the only member of the struct.
