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 structureand itssize is variable(can be changed be at runtime). 这其实就是在 heap 中分配的内存。 - The structure must contain at least
one more named memberin 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;
}
C99标准引入了Flexible Array Member特性,允许在结构体中声明一个未指定尺寸的数组,其大小在运行时可以变化。FAM必须作为结构体的最后一个成员,并且结构体至少还有一个其他命名成员。例如,`struct student`包含一个变长的`stud_name`数组。使用时,通过动态分配内存并根据用户提供的字符数组大小来初始化结构体。此特性在堆中分配内存,提高了内存利用率。
67

被折叠的 条评论
为什么被折叠?



