c++中用new申请动态内存,delete 清空内存
new申请成功返回正确的指针,不成功返回NULL;
在 类 中申请动态空间 需要在 构造函数 中申请、创建需要的数据结构
并且在析构函数中删除申请的空间
简单的new
//new 动态申请 数组 和 delete 所申请的空间 // new 操作失败时 返回NULL 否则返回首单元地址 #include <bits/stdc++.h> using namespace std; int main() { int *p,*q; p=new int (100); q=new int [10]; if(q==NULL){ cout<<"can't allocate more memory."<<endl; exit(1); } for(int i=0;i<10;i++) *(q+i)=i; delete p; delete []q; //delete 清空了new申请的空间 int a=10; p=&a; cout<<*p<<endl; //输出的是a 的值 return 0; }
在类中 动态创建二维数组
一个指向指针的指针,指向一个指针数组,指针数组指向各个元素
string**s = new string*[10]; for(int i=0;i<10;i++) s[i] =new string[10];
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 using namespace std; 3 class matrix 4 { 5 public: 6 matrix(string na="mark",string i="0000000"){ 7 one = new string*[10]; 8 for(int i=0;i<10;i++) 9 one[i] =new string[10]; 10 11 if(one==NULL){cout<<"can't allocate more memory"<<endl;exit(1);} 12 13 for(int i=1;i<10;i++) 14 for(int j=0;j<10;j++){ 15 one[i][j]=i%2?"1":"0"; 16 } 17 cout<<"allocate is finished"<<endl; 18 } 19 ~matrix(){ 20 for(int i=0;i<10;i++){ 21 for(int j=0;j<10;j++) 22 cout<<one[i][j]<<" "; 23 cout<<endl; 24 } 25 cout<<"delete is finished"<<endl; 26 } 27 private: 28 string **one; 29 }; 30 31 int main() 32 { 33 matrix a; 34 return 0; 35 }