一、柔性数组是什么?
也许你从来没有听说过柔性数组(flexible array)这个概念,但是它确实是存在的。
C99 中,结构中的最后一个元素允许是未知大小的数组,这就叫做『柔性数组』成员。
例如:
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
有些编译器会报错无法编译可以改成:
typedef struct st_type
{
int i;
int a[];//柔性数组成员
}type_a;
二、柔性数组的特点
(1)结构中的柔性数组成员前面必须至少一个其他成员。(2)sizeof 返回的这种结构大小不包括柔性数组的内存。(3)包含柔性数组成员的结构用 malloc () 函数进行内存的动态分配,并且分配的内存应该大于结构的大 小,以适应柔性数组的预期大小。
例如:
//code1
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
printf("%d\n", sizeof(type_a));//输出的是4
输出的结果为4,因为结构大小不包括柔性数组的大小
三、柔性数组的使用
//代码1
int i = 0;
type_a *p = (type_a*)malloc(sizeof(type_a)+100*sizeof(int));
//业务处理
p->i = 100;
for(i=0; i<100; i++)
{
p->a[i] = i;
}
free(p);
这样柔性数组成员a,相当于获得了100个整型元素的连续空间。
还可以使用realloc来扩展柔性数组的大小
int main()
{
struct type_a* ps =(struct type_a*) malloc(sizeof(struct type_a) + 40);//44字节
if (ps == NULL)
{
perror("malloc");
return 1;
}
ps->n = 100;
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i + 1;
}
//空间不够,需要增容
struct type_a* ptr = (struct type_a*)realloc(ps, sizeof(struct type_a)+ 60);
if (ptr == NULL)
{
perror("realloc");
return 1;
}
ps = ptr;
for (i = 0; i < 15; i++)
{
printf("%d\n",ps->arr[i]);
}
//释放
free(ps);
ps = NULL;
return 0;
}
四、柔性数组的优势
上述的
type_a
结构也可以设计为:
//代码2
typedef struct st_type
{
int i;
int *p_a;
}type_a;
int main()
{
//为结构体申请空间
struct type_a* ps = (struct type_a*)malloc(sizeof(struct type_a));
if (ps == NULL)
{
perror("malloc->ps");
}
ps->n = 100;
//为数组申请空间
int* pa = (int*)malloc(40);
if (pa == NULL)
{
perror("malloc->pa");
return 1;
}
ps->arr = pa;
//业务处理
int i = 0;
for (i = 0; i < 10; i++)
{
ps->arr[i] = i + 1;
}
//扩展空间
int* parr = realloc(ps->arr, 60);
if (parr == NULL)
{
perror("realloc->arr");
return 1;
}
ps->arr = parr;
for (i = 0; i < 15; i++)
{
printf("%d\n", ps->arr[i]);
}
//释放空间
free(ps->arr);
ps->arr = NULL;
free(ps);
ps = NULL;
return 0;
}
上述
代码
1
和
代码
2
可以完成同样的功能,但是
方法
1
的实现有两个好处:
第一个好处是:
方便内存释放
如果我们的代码是在一个给别人用的函数中,你在里面做了二次内存分配,并把整个结构体返回给 用户。用户调用free 可以释放结构体,但是用户并不知道这个结构体内的成员也需要 free ,所以你 不能指望用户来发现这个事。所以,如果我们把结构体的内存以及其成员要的内存一次性分配好 了,并返回给用户一个结构体指针,用户做一次free 就可以把所有的内存也给释放掉。
第二个好处是:
这样有利于访问速度
.
连续的内存有益于提高访问速度,也有益于减少内存碎片。(其实,我个人觉得也没多高了,反正 你跑不了要用做偏移量的加法来寻址)