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 天前
【51单片机】【protues仿真】基于51单片机的篮球计时计分器系统
c语言·stm32·单片机·嵌入式硬件·51单片机
小莞尔1 天前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
liujing102329291 天前
Day03_刷题niuke20250915
c语言
第七序章2 天前
【C++STL】list的详细用法和底层实现
c语言·c++·自然语言处理·list
l1t2 天前
利用DeepSeek实现服务器客户端模式的DuckDB原型
服务器·c语言·数据库·人工智能·postgresql·协议·duckdb
l1t2 天前
利用美团龙猫用libxml2编写XML转CSV文件C程序
xml·c语言·libxml2·解析器
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
你怎么知道我是队长2 天前
C语言---循环结构
c语言·开发语言·算法
程序猿编码2 天前
基于 Linux 内核模块的字符设备 FIFO 驱动设计与实现解析(C/C++代码实现)
linux·c语言·c++·内核模块·fifo·字符设备
mark-puls2 天前
C语言打印爱心
c语言·开发语言·算法