C语言之柔性数组
一.柔性数组
在含柔性数组的结构体中的最后一个元素是未知大小的数组。
#include<stdio.h>
typedef struct _FlexibleArray{
int i;
int array[];
} FlexibleArray;
int main()
{
printf("the struct size is %d\n",sizeof(FlexibleArray));//结果为4
}
我们为柔性数组分配空间后
#include<stdio.h>
#define MALLOC_ARRAY_SIZE 100
typedef struct _FlexibleArray{
int i;
int array[];
}FlexibleArray;
int main()
{
FlexibleArray *p=(FlexibleArray*)malloc(sizeof(FlexibleArray) + sizeof(int)*MALLOC_ARRAY_SIZE);
printf("After the malloc function the struct size is %d\n",sizeof(FlexibleArray));
free(p);
p = NULL;
return 0;
}
其结构体的大小仍然为4.
二.柔性数组的特点
1.结构体中的柔性数组成员前面必须至少一个其他成员。
2.sizeof返回这种结构大小不包括柔性数组的内存大小。
三.用途
满足变长度结构体的需要,解决使用数组时内存的冗余和数组的越界问题。常用于网络通信中构造不定长数据包,不会浪费空间网络流量,
如发送1024字节的数据,如果使用定长包,实际数据只有512字节时,就会浪费512字节的流量。
#include<stdio.h>
typedef struct _FlexibleArray{
int len;
int data[];
}FlexibleArray;
int main()
{
int len = 10;
int i = 0;
FlexibleArray *p=(FlexibleArray*)malloc(sizeof(FlexibleArray) + sizeof(int)*len);
p->len = len;
printf("After the malloc function the struct size is %d\n",sizeof(FlexibleArray));
for(i = 0; i < p->len; i++) {
p->data[i] = i + 1;
printf(" %d ", p->data[i]);
}
free(p);
p = NULL;
return 0;
}