动态内存开辟

目录

动态内存函数介绍

malloc函数 

free函数 

calloc函数

realloc函数 

 柔性数组

柔性数组使用 


动态内存函数介绍

malloc函数

calloc函数

realloc函数

free函数

malloc函数 

void *malloc( size_t size );

malloc函数用于申请一块连续可用的空间

申请成功,则返回这块空间起始地址

申请失败,则返回空指针

free函数 

void free( void *memblock );

free函数用来释放动态开辟的内存

free函数只能释放动态开辟内存!释放完要把指针置空!否则会出现野指针

若传入空指针,则free函数无意义。

int main()
{
	
	int* tmp = (int*)malloc(sizeof(int) * 100);
	if (tmp != NULL)
	{
		for (int i = 0; i < 100; i++)
		{
			*(tmp + i) = i;
			printf("%d ", *(tmp + i));
		}
	}
	free(tmp);
	tmp = NULL;
	return 0;
}

calloc函数

void *calloc( size_t num, size_t size );

calloc是为 num 个大小为 size 的元素开辟一块空间,并且把空间的每个字节初始化为0。 

其与malloc函数区别就是多了初始化功能。

int main()
{
	
	int* tmp = (int*)calloc(10,sizeof(int));
	if (tmp != NULL)
	{
		for (int i = 0; i < 10; i++)
		{
			
			printf("%d ", *(tmp + i));
		}
	}
	free(tmp);
	tmp = NULL;
	return 0;
}

realloc函数 

void *realloc( void *memblock, size_t size );

realloc函数用于调整动态开辟的内存大小

memblock 是要调整的内存地址 size 调整之后新大小 。

 柔性数组

typedef struct st_type
{
 int i;
 int a[0];//柔性数组成员
}type_a;


typedef struct st_type
{
 int i;
 int a[];//柔性数组成员
}type_a;

 结构体柔性数组成员前必有一个其他成员

sizeof返回的结构体大小不包括柔性数组大小。

动态开辟内存应大于结构体内存,以适应柔性数组。

typedef struct st_type
{
	int i;
	int a[0];//柔性数组成员
}type_a;
int main()
{
	printf("%d", (int)sizeof(type_a));//结果是4
}

柔性数组使用 

typedef struct st_type
{
	int i;
	int a[0];//柔性数组成员
}type_a;
int main()
{
	
	type_a* p = (type_a*)malloc(sizeof(type_a) + sizeof(int) * 100);
	if (p == NULL)
	{
	return 1;
	}
	//相当于a[100],为数组a开辟了100个整型大小
	free(p);
	p = NULL;//方便内存释放,只需要释放一次
	
	printf("%d", (int)sizeof(type_a));//结果是4
}

 上述有柔性数组也可以这样设计

typedef struct st_type
{
	int i;
	int* pa;
}type_a;
int main()
{//开辟空间
	type_a* p = (type_a*)malloc(sizeof(type_a));
	if (p == NULL)
	{
		return 1;
	}
	p->pa = (int*)malloc(sizeof(int) * 100);
	if (p->pa == NULL)
	{
		return 1;
	}
	//释放内存
	free(p->pa);
	p->pa = NULL;
	free(p);
	p = NULL;
}

通过上述对比,我们可以知道柔性数组的优点。

1.方便内存释放

2.有利于访问速度.(柔性数组内存开辟是连续的) 

 以上就是关于动态内存开辟的介绍。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嚞譶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值