什么是柔性数组
在C99中,结构体中的最后一个元素允许是位置大小的数组,这就叫柔性数组。
例如:
struct s
{
int n;
int arr[];//或者写成 int arr[0];
};
有的编译器都支持这两种写法,有的只支持其中一种。
柔性数组特点
1.在结构体中,柔性数组前面必须至少有一个其他成员
2.sizeof 返回的这种结构体大小不包括柔性数组的内存
3.包含柔性数组成员的结构体用malloc()函数进行内存动态分配,并且分配的内存应该大于结构体大小,以适应柔性数组的预期大小。
用例
#include<stdio.h>
struct s
{
int n;
int arr[];//或者写成 int arr[0];
};
int main()
{
//动态开辟空间
struct s* ps = (struct s*)malloc(sizeof(struct s)+40);//预留的40个字节给arr数组
if(ps==NULL)
{
perror("error:");
return 1;
}
//如果不够用,扩容
struct s* ptr = (struct s*)realloc(ps, sizeof(struct s) + 80);
if (ptr == NULL)
{
perror("error:");
return 1;
}
ps = ptr;
//使用
//....
//释放
free(ps);
ps = NULL;
return 0;
}
这里的动态开辟,让数组柔性可变。
比较
struct s
{
int n;
int *arr;
};
把柔性数组换成 int*arr 呢?
#include<stdio.h>
struct s
{
int n;
int* arr;
};
int main()
{
struct s* ps = (struct s*)malloc(sizeof(struct s));
if (ps == NULL)
{
perror("erroe:");
return 1;
}
//若开辟成功,向数组后面开辟空间
ps->arr = (int *)malloc(40);
if (ps->arr == NULL)
{
return 1;
}
// 开辟成功
//使用....
//如果不够用,再去realloc扩容
//最后释放
free(ps->arr);
free(ps);
ps = NULL;
return 0;
}
对比来看,柔性数组好处是:
1.方便内存释放1次(如果malloc越多,释放越多,内存碎片就越多,容易空间泄露)
2.有利于访问速度(连续的内存,有利于提高访问速度)
推荐博客
链接: link
看看大佬怎么谈柔性数组的吧!