C++中動態申請二維陣列並釋放方法
阿新 • • 發佈:2019-02-19
C/C++中動態開闢一維、二維陣列是非常常用的,以前沒記住,做題時怎麼也想不起來,現在好好整理一下。
C++中有三種方法來動態申請多維陣列
(1)C中的malloc/free
(2)C++中的new/delete
(3)STL容器中的vector
下面逐一介紹:
第一種:malloc/free
1.動態開闢一維陣列
//動態開闢一維陣列 void dynamicCreate1Array() { int m; int i; int *p; printf("請輸入開闢的陣列長度:"); scanf("%d",&m); p = (int*)malloc(sizeof(int)*m);//動態開闢 printf("請輸入資料:"); for(i = 0; i < m ; i++) scanf("%d",&p[i]); printf("輸出資料:\n"); for(i = 0; i < m; i++) printf("%d ",p[i]); free(p); }
執行結果:
2.動態開闢二維陣列
//動態開闢二維陣列 void dynamicCreate2Array() { int m,n; int i,j; int **p; printf("請輸入陣列行和列:"); scanf("%d%d",&m,&n); p = (int**)malloc(sizeof(int*)*m); //開闢行 for(i = 0; i < m; i++) { *(p+i) = (int*)malloc(sizeof(int)*n);//開闢列 } //輸入資料 printf("請輸入數:"); for(i = 0 ; i < m;i++) for(j = 0; j < n;j++) scanf("%d",&p[i][j]); //輸出資料 for(i = 0 ; i < m;i++) { for(j = 0; j < n;j++) { printf("%3d ",p[i][j]); } printf("\n"); } //釋放開闢的二維空間 for(i = 0; i < m;i++) free(*(p+i)); }
執行結果:
第二種:new/delete
1.動態開闢一維陣列
void DynamicCreate1Array() { int len; cout<<"請輸入長度:"; cin>>len; int *p = new int[len]; cout<<"請輸入資料:"; for(int i = 0; i < len; i++) cin>>p[i]; cout<<"輸出資料:"<<endl; for(i = 0; i < len; i++) cout<<setw(4)<<p[i]; delete[] p; }
2.動態開闢二維陣列
void DynamicCreate2Array()
{
int m,n;
cout<<"請輸入行和列:";
cin>>m>>n;
//動態開闢空間
int **p = new int*[m]; //開闢行
for(int i = 0; i < m; i++)
p[i] = new int[n]; //開闢列
cout<<"請輸入資料:";
for(i = 0 ; i < m ; i++)
for(int j = 0; j < n; j++)
cin>>p[i][j];
cout<<"輸出資料:"<<endl;
for(i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
cout<<setw(3)<<p[i][j];
cout<<endl;
}
//釋放開闢的資源
for(i = 0; i < m; i++)
delete[] p[i];
delete[] p;
}
第三種:STL中的vector
動態開闢二維陣列
void VectorCreate()
{
int m,n;
cout<<"請輸入行和列:";
cin>>m>>n;
//注意下面這一行:vector <int後兩個 "> "之間要有空格!否則會被認為是過載 "> > "。
vector<vector<int> > p(m,vector<int>(n));
cout<<"請輸入資料:";
for(int i = 0 ; i < m ; i++)
for(int j = 0; j < n; j++)
cin>>p[i][j];
cout<<"輸出資料:"<<endl;
for(i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
cout<<setw(3)<<p[i][j];
cout<<endl;
}
}
轉載請標明出處:http://blog.csdn.net/u012027907