柔性数组
C99中,结构中的最后一个元素允许是未知大小的数组,就叫做柔性数组成员。
注意:1.柔性数组成员前必须有其他成员
2.sizeof返回的这种结构大小不包括柔性数组的内存
3.包含柔性数组成员的结构用malloc()函数进行内存的动态分配,且分配的内存应该大于结构的大小,以适应柔性数组的预期大小
#include<stdio.h>
#include<stdlib.h>
struct S
{
int n;
int arr[];//柔性数组成员
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S) + 40);
if (ps == NULL)
{
//...最好加一个报错
return 1;
}//使用动态内存开辟时要注意是否开辟成功
//使用...
//扩容
struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 80);
if (ptr != NULL)
{
ps = ptr;
ptr = NULL;
}
//释放
free(ps);
ps = NULL;
return 0;
}