c++利用new在堆区开辟数据,用delete手动释放。
new在堆区开辟数据会返回对应数据类型的指针。
基本语法:
int main ()
{
int *p=new int(10);//在堆区开辟数据
cout << *p << endl;
delete p;//用完数据后,释放数据
cout << *p << endl;//再次访问就会输出乱码
return 0;
}
开辟数组:
int main ()
{
int * arr=new int[10];//开辟数组用 [ ]
int i;
for(i=0 ; i<10 ; i++)
arr[i]=i; //正常给数组初始化
for(i=0 ; i<10 ; i++)
cout<< arr[i] <<endl;
delete [] arr;//释放数组 ,注意 [ ]
for(i=0 ; i<10 ; i++)
cout<< arr[i] <<endl; //释放后在访问就是错误结果
return 0;
}