柔性数组可以动态开辟空间,数组大小不固定;柔性数组必须是结构体中的最后一个成员,并且不是第一个成员。
优点:只需开辟一次空间,在内存中存储是连续的,可以提高访问速度,并且方便内存释放。
struct s
{
int n ;
char a[];//柔性数组是最后一个成员,并且前面必须有一个成员
};
int main()
{
struct s* ps = (struct s*)malloc(sizeof(struct s) + sizeof(char) * 10);//根据需求为数组申请空间
if (ps == NULL)
{
perror("malloc");//开辟失败报错
}
int i = 0;
for (i = 0; i < 10; i++)
{
ps->a[i] = 'q';
}
for (i = 0; i < 10; i++)
{
printf("%c ", ps->a[i]);
}
printf("\n");
struct s* ptr = (struct s*)realloc(ps,sizeof(struct s) + sizeof(char) * 20);//修改数组大小,增量
if (ptr != NULL)
{
ps = ptr;
}
else
{
perror("realloc");
return 1;
}
for (i = 10; i < 20; i++)
{
ps->a[i] = 'j';
}
for (i = 10; i < 20; i++)
{
printf("%c ", ps->a[i]);
}
free(ps);//释放内存
ps = NULL;
return 0;
}