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;
}
相关推荐
SoveTingღ20 小时前
【C语言】什么是野指针?
c语言·指针·嵌入式软件
lowhot20 小时前
C语言UI框架
c语言·开发语言·笔记·ui
ベadvance courageouslyミ21 小时前
项目一(线程邮箱)
c语言·线程·makefile·进程间通信·线程邮箱
Herbert_hwt1 天前
C语言表达式求值详解:从原理到实战的完整指南
c语言
朔北之忘 Clancy1 天前
2025 年 6 月青少年软编等考 C 语言一级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
梁山1号1 天前
【关于CAN】
c语言·stm32·单片机
VekiSon1 天前
综合项目实战——电子商城信息查询系统
linux·c语言·网络·http·html·tcp·sqlite3
客卿1231 天前
C语言刷题--合并有序数组
java·c语言·算法
无限码力1 天前
华为OD机试真题双机位C卷 【运维日志排序】C语言实现
c语言·华为od·华为od机考·华为od机试真题·华为od机试双机位c卷·华为od机考双机位c卷·华为od上机考试
小郭团队1 天前
未来PLC会消失吗?会被嵌入式系统取代吗?
c语言·人工智能·python·嵌入式硬件·架构