C语言复习--柔性数组

柔性数组是C99中提出的一个概念.结构体中的最后⼀个元素允许是未知大小的数组,这就叫做柔性数组成员。

格式大概如下

struct S

{

int a;

char b;

int arr[];//柔性数组

};

也可以写成

struct S

{

int a;

char b;

int arr[0];//柔性数组

};

柔性数组的特点

柔性数组的使用

cpp 复制代码
#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;
}

柔性数组的优势

上面的代码也可以用下面的代码来实现.两者功能完全相同.

cpp 复制代码
#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;
}

以上就是我了解到的柔性数组了.希望有所帮助.

相关推荐
我能坚持多久1 个月前
D19—C语言动态内存管理全解:从malloc到柔性数组
c语言·开发语言·柔性数组
我是大咖1 个月前
关于柔性数组的理解
数据结构·算法·柔性数组
Allen_LVyingbo2 个月前
面向“病历生成 + CDI/ICD”多智能体系统的选型策略与落地实践(三)
算法·自然语言处理·性能优化·知识图谱·健康医疗·柔性数组
栈与堆2 个月前
数据结构篇(1) - 5000字细嗦什么是数组!!!
java·开发语言·数据结构·python·算法·leetcode·柔性数组
yuanmenghao2 个月前
自动驾驶中间件iceoryx - 内存与 Chunk 管理(一)
c++·vscode·算法·链表·中间件·自动驾驶·柔性数组
山上三树2 个月前
柔性数组(C语言)
c语言·开发语言·柔性数组
黎雁·泠崖2 个月前
C 语言动态内存管理高阶:柔性数组特性 + 程序内存区域划分全解
c语言·开发语言·柔性数组
A***27953 个月前
ReactGraphQL案例
spring boot·spring cloud·柔性数组
番茄大杀手5 个月前
C/C++柔性数组
c语言·柔性数组
西阳未落6 个月前
C语言柔性数组详解与应用
c语言·开发语言·柔性数组