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;
}
相关推荐
leo__5205 小时前
IEC 104 协议 C 语言实现
c语言·数据库
啧不应该啊7 小时前
Day1 Python 与 C 的类型区别
c语言·开发语言
cen__y7 小时前
Linux07(信号01)
linux·运维·服务器·c语言·开发语言
木木_王11 小时前
嵌入式Linux学习 | 数据结构 (Day05) 栈与队列详解(原理 + C 语言实现 + 实战实验 + 易错点剖析)
linux·c语言·开发语言·数据结构·笔记·学习
Joseph Cooper12 小时前
Linux HID 子系统实战:从虚拟键盘到 input 事件上报
linux·c语言·计算机外设
啧不应该啊13 小时前
Day1 python与c宏观区别
c语言·开发语言
OneT1me13 小时前
CVE-2026-31431 的C语言版本
c语言·开发语言·安全威胁分析
爱编码的小八嘎14 小时前
C‘语言完美演绎9-11
c语言
一行代码一行诗++15 小时前
C语言中if的使用
c语言·c++·算法
来生硬件工程师15 小时前
【程序库】 MutiButton 按键库
c语言·笔记·stm32·单片机·mcu·嵌入式实时数据库