Flexible Array Members in a structure in C

C99标准引入了Flexible Array Member特性,允许在结构体中声明一个未指定尺寸的数组,其大小在运行时可以变化。FAM必须作为结构体的最后一个成员,并且结构体至少还有一个其他命名成员。例如,`struct student`包含一个变长的`stud_name`数组。使用时,通过动态分配内存并根据用户提供的字符数组大小来初始化结构体。此特性在堆中分配内存,提高了内存利用率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Flexible Array Member(FAM)

Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language. C99 标准里的。

  1. 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.
  2. Such an array inside the structure should preferably be declared as the last member of structure and its size is variable(can be changed be at runtime). 这其实就是在 heap 中分配的内存。
  3. 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;
 }

Reference

  1. flexible-array-members-structure-c
  2. http://redisbook.com/preview/sds/implementation.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值