Flexible Array Member(FAM)
Flexible Array Member(FAM)
is a feature introduced in the C99 standard
of the C programming language. C99 标准里的。
- For the structures in C programming language from
C99 standard onwards
, we can declare an array without a dimension and whose size is flexible in nature. - Such an array inside the structure should preferably be declared as the
last member of structure
and itssize is variable(can be changed be at runtime)
. 这其实就是在 heap 中分配的内存。 - The structure must contain at least
one more named member
in addition to the flexible array member. FAM 必须是结构体的最后一个成员。
举例
struct student
{
int stud_id; // stack memory
int name_len; // stack memory
int struct_size; // stack memory,stud_name 长度 + sizeof(struct student *)。
char stud_name[]; // heap memory,其实就是个 char* 类型的指针。所以这里就是变长字段。这个不计入 sizeof(struct student)
};
如何使用?
// Memory allocation and initialisation of structure
struct student *createStudent(struct student *s, int id, char a[])
{ // Allocating memory according to user provided
// array of characters
// student 指针大小 + stud_name 长度
s = malloc( sizeof(*s) + sizeof(char) * strlen(a));
s->stud_id = id;
s->name_len = strlen(a);
strcpy(s->stud_name, a);
// Assigning size according to size of stud_name
// which is a copy of user provided array a[].
s->struct_size = (sizeof(*s) + sizeof(char) * strlen(s->stud_name));
return s;
}