C++堆内存处理

1.利用 new 关键字创建堆区数据

#include <iostream>
using namespace std;

int *func()
{
	//利用new关键字,可以将数据开辟到堆区
	//指针本质是局部变量,放在栈上,指针保存的数据放在堆区
	int *p=new int(10);
	return p;
}

int main()
{
	//在堆区开辟数据
	int *p=func();
	
	cout<<*p<<endl;

	system("pause");
	return 0;
}

堆区数据由程序员管理开辟和释放
堆区数据利用new关键字进行开辟内存

2.在堆区利用new开辟数组

#include <iostream>
using namespace std;

void test02()
{
	//创建10整形数据的数组,在堆区
	int * arr=new int [10];
	
	for (int i=0;i<10;i++)
	{
		arr[i]=i+100;
	}
	
	for (int i=0;i<10;i++)
	{
		cout<<arr[i]<<endl;
	}
	
	//释放堆区数组
	//释放数组的时候,要加[]
	delete []arr;
}

int main()
{
	test02();
	
	system("pause");
	return 0;
}

3.delete 关键字

#include <iostream>
using namespace std;

int *func()
{
	//在堆区创建整型数据
	//new返回该数据类型的指针
	int * p=new int(10);
	return p;
}

void test01()
{
	int *p=func();
	cout<< *p <<endl;
	//堆区数据由程序员管理开辟,程序员管理释放
	//如果想释放堆区数据,使用关键字 delete
	delete p;
	cout<< *p <<endl;
	//内存已经被释放,再次访问就是非法操作,会报错
}

int main()
{
	test01();
	
	system("pause");
	return 0;
}

堆区开辟的数据,由程序员手动开辟,手动释放,释放利用操作符delete

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值