一、柔性数组概念
C99中,结构体中的最后一个元素允许是未知大小的数组,这叫做柔性数组成员。
struct S
{
char c;
int n;
int arr[];//柔性数组
};
有些编译器会报错,可以修改为:
struct S
{
char c;
int n;
int arr[0];//柔性数组
};
二、柔性数组的特点
1.结构体中的柔性数组成员前面必须至少一个其他成员。
2.sizeof返回的这种结构大小不包含柔性数组的内存。
3.包含柔性数组成员的结构用malloc()函数进行内存的动态分配,并且分配的内存应该大于结构体的大小,以适应柔性数组的预期大小。
#include<stdio.h>
typedef struct st_type
{
int i;
int a[0];//柔性数组成员
}type_a;
int main()
{
printf("%d\n", sizeof(type_a));//输出的是4
return 0;
}
三、柔性数组的使用
//代码1
#include<stdio.h>
#include<stdlib.h>
struct S
{
int n;
int arr[];
};
int main()
{
struct S* p