C指针开辟内存空间

动态内存管理

使用malloc,calloc函数动态开辟内存空间,但要注意使用后要使用free函数进行释放。

方式一:动态开辟内存

#include <stdio.h>


int* getSpace()
{
	//开辟5个连续的int大小的内存
	int* p = malloc(sizeof(int) * 5);
	if (p == NULL)
	{
		return;
	}
	//赋值
	for (int i = 0; i < 5; i++)
	{
		p[i] = i + 100;
	}
	//返回开辟好的内存指针
	return p;
}

void test()
{
	int* p = getSpace();
	for (int i = 0; i < 5; i++)
	{
		printf("%d\n", p[i]);
	}
	//手动开辟  手动释放
	free(p);
	//避免出现野指针
	p = NULL;
}

在这里插入图片描述

方式二:动态开辟内存

//高一级的指针
void allocateSpace(char** pp)
{
	//开辟100个内存
	char* temp = malloc(100);
	//全部赋值为0
	memset(temp, 0, 100);
	//复制"hello world"到temp
	strcpy(temp, "hello world");
	*pp = temp;
}
void test()
{
	char* p = NULL;
	allocateSpace(&p);
	printf("%s\n", p);
	if (p != NULL)
	{
		free(p);
		p = NULL;
	}
}

给指针进行开辟内存时,被调函数不能使用同级指针,要使用指针的地址(高一级的指针),被调函数接收这个地址后再进行内存开辟。即 主调函数没有分配内存,被调函数需要用更高级的指针去修饰低级指针,进行分配内存
在这里插入图片描述

以下方式错误

void allocateSpace(char* pp)
{
	char* temp = malloc(100);
	memset(temp, 0, 100);
	strcpy(temp, "hello world");
	pp = temp;
}
  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值