當給定的條件不同時,二維數組的動態分配方式不同。例如,已知二維數組的行數(即第一維維度)爲多少的情況下對其進行動態分配,與知道列數(第二維維度),或者兩個維度都未知的情況下,二維數組的動態分配方式都不同,對應的釋放方式也不同。下面我們就來一一介紹。
1. 已知二維數組的行數
const int ROW=3;//已知行數
int *a[ROW];//指針數組
int col; //列數爲未知,動態輸入
cin>>col;
//動態分配
for(int i=0;i<ROW;i++){
a[i]=new int[col];
/*輸入數組元素
for (int j = 0; j < col; j++){
cin >> a[i][j];
}*/
}
/*打印數組
for (int i = 0; i < M; i++){
for (int j = 0; j < col; j++){
cout << a[i][j] << " ";
}
cout << endl;
}
*/
//釋放
for(int i=0;i<ROW;i++){
delete[] a[i];
}
上述方法中指針指向的數組在內存中並不一定是連續存放的,如果需要保持內存的連續性,則需要一次分配內存。
1.1 已知二維數組的行數,一次分配內存(保持內存的連續性)
const int ROW=3;//已知行數
int *a[ROW];//指針數組
int col; //列數爲未知,動態輸入
cin<<col;
//動態分配
a[0]=new int[ROW*col];
for(int i=1;i<ROW;i++){
a[i]=a[i-1]+col;
}
//釋放
delete[] a[0];
2. 已知二維數組的列數
const int COL=2;//已知列數
int (*a)[COL];//數組指針
int row;//行數爲未知,動態輸入
cin<<row;
//動態分配
a=new int[row][COL];
//釋放
delete[] a;
3. 未知二維數組的行數和列數
int **a;//指針的指針
int row,col;//未知行數和列數,動態輸入
cin<<row<<col;
//動態分配
a=new int*[row];
for(int i=0;i<row;i++){
a[i]=new int[col];
}
//釋放
for(int i=0;i<row;i++){
delete[] a[i];
}
delete[] a;
同樣的,上述方法中指針指向的數組在內存中也不一定是連續存放的,如果需要保持內存的連續性,則需要一次分配內存。
3.1 未知二維數組的行數和列數,一次分配內存(保持內存的連續性)
int **a;//指針的指針
int row,col;//未知行數和列數,動態輸入
cin<<row<<col;
//動態分配
a=new int*[row];
a[0]=new int[row*col]
for(int i=1;i<row;i++){
a[i]=a[i-1]+col;
}
//釋放
delete[] a[0];
delete[] a;
特別注意一下,new和delete要配對使用,有多少個new就有多少個delete,且new和delete的形式保持一致,這樣纔可以避免內存泄漏。