C语言复习--柔性数组
柔性数组是C99中提出的一个概念.结构体中的最后⼀个元素允许是未知大小的数组,这就叫做柔性数组成员。
格式大概如下
struct S
{
int a;
char b;
int arr[];//柔性数组
};也可以写成
struct S
{
int a;
char b;
int arr[0];//柔性数组
};
柔性数组的特点
柔性数组的使用
#include<assert.h>
struct S
{int a;char b;int arr[];//柔性数组
};
int main()
{//柔性数组和其所在的结构体的空间都是malloc来的struct S* ptr = (struct S*)malloc(sizeof(struct S) + sizeof(int) * 10);assert(ptr);ptr->a = 10;ptr->b = 'x';for (int i = 0; i < 10; i++){*(ptr->arr + i) = i;}printf("%d %c\n", ptr->a, ptr->b);for (int i = 0; i < 10; i++){printf("%d ", ptr->arr[i]);}printf("\n");//如果觉得空间不够还可以用realloc来扩容//要释放空间free(ptr);ptr = NULL;return 0;
}
柔性数组的优势
上面的代码也可以用下面的代码来实现.两者功能完全相同.
#include<assert.h>
struct S
{int a;char b;int* arr;//柔性数组
};
int main()
{struct S* ptr = (struct S*)malloc(sizeof(struct S));assert(ptr);ptr->arr = (int*)malloc(sizeof(int) * 10);assert(ptr->arr);ptr->a = 10;ptr->b = 'x';for (int i = 0; i < 10; i++){*(ptr->arr + i) = i;}printf("%d %c\n", ptr->a, ptr->b);for (int i = 0; i < 10; i++){printf("%d ", ptr->arr[i]);}printf("\n");free(ptr->arr);ptr->arr = NULL;free(ptr);ptr = NULL;return 0;
}
以上就是我了解到的柔性数组了.希望有所帮助.