C++如何创建、删除(释放内存)动态二维数组make2dArray

直接上代码

思想是利用二维数组的指针进行空间的分配。

#include 
using namespace std;
template <class T>
void make2dArray(T ** & x,int rows, int cols){
    x = new T*[rows];
    for (int i = 0; i < rows; ++i)
    {
        x[i] = new T[cols];
    }
}

下面是释放内存的方法:

template <class T>
void delete2dArray(T** &x, int rows) {
    for (int i = 0; i < rows; ++i)
    {
        delete [] x[i];
    }
    delete [] x;
    x = NULL;
}

下面是输出该二维数组的代码

template<class T>
void show(T** &A,int rows, int cols)
{
    for(int i = 0; i for (int ii = 0; ii < cols; ++ii)
        {
            cout << A[i][ii];
        }
        cout << endl;
    }
}

你可能感兴趣的:(心得经验)