目录
一.柔性数组的特点
struct S
{
int x;
int a[];
};
int main()
{
printf("%d", sizeof(S));
}
这段代码的输出是什么?
我们打印结构体S所占空间的大小,这个a[]占多少字节呢?
输出结果是4,可一个int类型的x就是4了,a[]去哪了?好奇怪哦。
原来,这是一种柔性数组。
二.柔性数组的使用
1.如何使用柔性数组
包含柔数组成员的结构用malloc函数进行内存的动态分配,
且分配的内存应该大于结构的大小,以适应柔性数组的预期大小。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct S
{
int x;
int a[];
};
int main()
{
//为柔性数组a[]开辟了40个字节的空间
struct S *ps =(struct S*)malloc(sizeof(struct S) + 40);
if (ps == NULL) //检查是否为空指针
{
perror("ps");
return 1;
}
ps->x = 10;
int i = 0;
for (i = 0; i < 10; i++)
{
ps->a[i] = i; //数组使用
}
for (i = 0; i < 10; i++)
{
printf("%d ",ps->a[i]); //数组打印
}
//若觉得40不够用,可用realloc扩容
//如:
struct S* ptr = (struct S*)realloc(ps, sizeof(struct S) + 80);
if (ptr == NULL) //检查是否为空指针
{
perror("realloc");
return 1;
}
else
{
ps = ptr;
}
free(ps); //释放内存并置为空指针
ps = NULL;
}
2.不用柔性数组的话有什么代替
我们经常用字符串指针来申请空间,
那我们直接给字符串指针malloc一块空间,不就行了吗,
为什么还要用柔性数组呢?
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
struct S
{
int x;
int *a;
};
int main()
{
struct S* ps = (struct S*)malloc(sizeof(struct S) );//为结构体变量x开辟空间
if (ps == NULL)
{
return 1;
}
ps->a = (int*)malloc(40); //为字符串指针开辟40个字节的空间
if (ps->a == NULL)
{
free(ps);
ps = NULL;
return 1;
}
free(ps->a);
ps->a = NULL;
free(ps);
ps = NULL;
}
上述代码确实可以完成相同的功能,
但是柔性数组相对而言更好。
让我们来看看柔性数组的优势。
三.柔性数组的优势