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;
}
相关推荐
小辉懂编程5 小时前
C语言:51单片机实现数码管依次循环显示【1~F】课堂练习
c语言·开发语言·51单片机
Inverse1627 小时前
C语言_动态内存管理
c语言·数据结构·算法
whoarethenext8 小时前
c/c++的opencv的轮廓匹配初识
c语言·c++·opencv
apocelipes9 小时前
使用libdivide加速整数除法运算
c语言·c++·性能优化·linux编程
青出于兰9 小时前
C语言| 指针变量的定义
c语言·开发语言
思茂信息15 小时前
CST软件对OPERA&CST软件联合仿真汽车无线充电站对人体的影响
c语言·开发语言·人工智能·matlab·汽车·软件构建
川川菜鸟15 小时前
2025长三角数学建模C题完整思路
c语言·开发语言·数学建模
云海听雷16 小时前
C语言中字符串函数的详细讲解
c语言·笔记·学习
C++ 老炮儿的技术栈16 小时前
自定义CString类与MFC CString类接口对比
c语言·c++·windows·qt·mfc
人类恶.16 小时前
C 语言学习笔记(数组)
c语言·笔记·学习