一、概念
struct s//占4个字节
{
int i;
int a[0];//柔性数组成员
};
有些编译器会报错无法编译可以改成:
struct s//占4个字节
{
int i;
int a[];//柔性数组成员
};
柔性数组的特点:
1、结构中的柔性数组成员前面必须至少一个其他成员。
2、sizeof 返回的这种结构大小不包括柔性数组的内存。
3、包含柔性数组成员的结构用malloc ()函数进行内存的动态分配,并且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。
二、使用
//代码1
#include<stdio.h>
#include<stdlib.h>
struct s
{
int i;
int a[0];//柔性数组成员
};
int main()
{
int i = 0;
struct s* ps = (struct s*)malloc(sizeof(struct s) + 10 * sizeof(int));
for ( i = 0; i < 10; i++)
{
ps->a[i] = i;
}
for ( i = 0; i < 10; i++)
{
printf("%d ", ps->a[i]);
}
free(ps);
ps=NULL;
return 0;
}
三、优势
//代码2
#include<stdio.h>
#include<stdlib.h>
struct s
{
int i;
int* a;//指针
};
int main()
{
int i = 0;
struct s* ps = (struct s*)malloc(sizeof(struct s));
ps->a = (int*)malloc(10 * sizeof(int));
for ( i = 0; i < 10; i++)
{
ps->a[i] = i;
}
for ( i = 0; i < 10; i++)
{
printf("%d ", ps->a[i]);
}
free(ps->a);
ps->a = NULL;
free(ps);
ps = NULL;
return 0;
}
第一个好处是:方便内存释放,代码1释放一次,代码2释放多次。
第二个好处是:这样有利于访问速度,也有益于减少内存碎片。 代码1在内存中开辟的空间是连续的,代码2内存中开辟的空间是间断的。