C语言柔性数组

C99中结构体最后一个成员允许一个大小未知的数组

sizeof 返回的这种结构大小不包括柔性数组的内存

c 复制代码
struct s
{
	int n; 
	int arr[];//柔性数组成员
};
int main()
{
	int sz = sizeof(struct  s);
	printf("%d\n", sz); //4

	return 0;
}

包含柔性数组成员的结构用malloc ()函数进行内存的动态分配,并且分配的内存应该大于结构的大 小,以适应柔性数组的预期大小。

两种实现,推荐第一种

第一种

c 复制代码
	struct s* ps = (struct s*)malloc(sizeof(struct s) + 40);

	if (ps == NULL)
		return 1;
	ps->n == 100;
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->arr[i] = i;

	}
	for (i = 0; i < 10; i++)
	{
		printf("%d ", ps->arr[i]);

	}

	struct s* ptr = realloc(ps, sizeof(struct s) + 80);
	if (ptr != NULL)
	{
		ps = ptr;
	}
	free(ps);
	ps = NULL;

第二种

c 复制代码
struct s
{
	int n;
	int* arr;
};
int main()
{
	struct s* ps = (struct s*)malloc(sizeof(struct s));
	if (ps == NULL)
		return 1;
	ps->n = 100;
	ps->arr = (int*)malloc(40);
	if (ps->arr == NULL)
		return 1;
	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->arr[i] = i;

	}
	for (i = 0; i < 10; i++)
	{
		printf("%d ", ps->arr[i]);

	}
	
	//扩容
	int* ptr = (int*)realloc(ps->arr,80);
	if (ptr == NULL)
		return 1;
	else
		ps = ptr;

	//释放
	free(ps->arr);
	free(ps);
	ps = NULL;

	return 0;
}
相关推荐
冷静 包容1 小时前
C语言学习之 没有重复项数字的全排列
c语言·开发语言·学习
ROBIN__dyc2 小时前
C语言基本概念
c语言·开发语言
不穿格子衬衫11 小时前
常用排序算法(下)
c语言·开发语言·数据结构·算法·排序算法·八大排序
aqua353574235811 小时前
蓝桥杯-财务管理
java·c语言·数据结构·算法
Word码12 小时前
数据结构:栈和队列
c语言·开发语言·数据结构·经验分享·笔记·算法
五花肉村长12 小时前
数据结构-队列
c语言·开发语言·数据结构·算法·visualstudio·编辑器
qinzechen12 小时前
分享几个做题网站------学习网------工具网;
java·c语言·c++·python·c#
yttandb14 小时前
重生到现代之从零开始的C语言生活》—— 内存的存储
c语言·开发语言·生活
结衣结衣.14 小时前
python中的函数介绍
java·c语言·开发语言·前端·笔记·python·学习
五味香15 小时前
C++学习,信号处理
android·c语言·开发语言·c++·学习·算法·信号处理