什么是柔性数组

文章展示了如何在C语言中使用柔性数组,通过malloc和realloc函数动态分配和调整内存大小。柔性数组作为结构体的最后一个成员,允许在内存中存储连续的数据,从而提高访问速度。代码示例演示了初始化、修改数组大小及释放内存的过程。
摘要由CSDN通过智能技术生成

柔性数组可以动态开辟空间,数组大小不固定;柔性数组必须是结构体中的最后一个成员,并且不是第一个成员。

优点:只需开辟一次空间,在内存中存储是连续的,可以提高访问速度,并且方便内存释放。

struct s
{
	int n ;
	char a[];//柔性数组是最后一个成员,并且前面必须有一个成员
};
int main()
{
	struct s* ps = (struct s*)malloc(sizeof(struct s) + sizeof(char) * 10);//根据需求为数组申请空间
	if (ps == NULL)
	{
		perror("malloc");//开辟失败报错
	}

	int i = 0;
	for (i = 0; i < 10; i++)
	{
		ps->a[i] = 'q';
	}
	for (i = 0; i < 10; i++)
	{
		printf("%c ", ps->a[i]);
	}
	printf("\n");

	struct s* ptr = (struct s*)realloc(ps,sizeof(struct s) + sizeof(char) * 20);//修改数组大小,增量
	if (ptr != NULL)
	{
		ps = ptr;
	}
	else
	{
		perror("realloc");
		return 1;
	}
	for (i = 10; i < 20; i++)
	{
		ps->a[i] = 'j';
	}
	for (i = 10; i < 20; i++)
	{
		printf("%c ", ps->a[i]);
	}


	free(ps);//释放内存
	ps = NULL;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值