#include<iostream>
#include<cstdlib>
#include<iomanip>
#include"windows.h"
using namespace std;
template <typename T>
void Creat_two_array(T **&x, const int &row,const int &col)
{
x = new T *[row];
for (int i = 0; i < row; i++)
x[i] = new T[col];
}
template<typename T>
void Release(T ** &x, const int &row)
{
for (int j = 0; j < row; j++)
delete [] x[j];
delete [] x;
x = nullptr;//防止再次访问释放的内存
}
int main()
{
//列已知的二维数组创建
int n;
cout << "Please input the row of array(column=5):";
cin >> n;
cout << "please input each elements of array.\n";
int(*p)[5];//只知道列长度
try{ p = new int[n][5]; }
catch (bad_alloc e)
{
cerr << "Out of memory" << endl;
exit(EXIT_FAILURE);
}
for (int i = 0; i < n;i++)
for (int j = 0; j < 5; j++)
cin >> p[i][j];
cout << "This array is:\n";
cout.setf(ios_base::right, ios_base::adjustfield);//fmtflags
for (int i = 0; i < n; i++)
{
for (int j = 0; j < 5; j++)
cout << setw(3) << p[i][j];
cout << endl;
}
delete[] p;
//动态分配行列均不知道的二维数组
int col, row,**num;
cout << "please input two number(row,column):";
cin >> row >> col;
Creat_two_array<int>(num, row, col);
cout << "please input each elements of array.\n";
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
cin >> num[i][j];
cout << "This array is:\n";
cout.setf(ios_base::left, ios_base::adjustfield);//fmtflags
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
cout << setw(3) << num[i][j];
cout << endl;
}
Release<int>(num, row);
system("pause");
return 0;
}
程序运行结果如下