根據輸入的行列數,動態開闢二維數組空間。代碼如下:
#include <iostream>
using namespace std;
int main()
{
int row, col; //矩陣行列
cout << "Row: ";
cin >> row;
cout << "Col: ";
cin >> col;
int** p_p_int = new int*[row];
for (int i = 0; i < row; i++)
{
p_p_int[i] = new int[col];
}
int count = 0;
for (int m = 0; m < row; m++)
{
for (int n = 0; n < col; n++)
{
p_p_int[m][n] = count++;
}
}
cout << "----------Matrix----------" << endl;
for (int m = 0; m < row; m++)
{
for (int n = 0; n < col; n++)
{
cout << p_p_int[m][n] << " ";
}
cout << endl;
}
for (int j = 0; j < row; j++) //釋放每行指針
{
delete [] p_p_int[j];
}
delete [] p_p_int; //釋放指向行的指針
return 0;
}
需要注意指向指針的指針和二維數組在物理存儲上的區別。(二維數組爲線性連續存儲,指向指針的指針一般佔用的不連續的內存。)