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