Let me talk about the dynamic memory allocation of dynamic multi-dimensional arrays here, and only talk about the dynamic memory allocation of fixed-size arrays. The situation of unfixed arrays will be more complicated.
#include <iostream>
using namespace std;
//动态分配二维数组
int main()
{
const int dim = 3;
//动态分配一维数组
//然后将指针转换为二维数组的指针
//也就是指向一维数组的指针
int *ptr = new int [dim * dim];
int (*mat)[dim] = (int (*)[dim])ptr;
for ( int i = 0;i < dim; i++)
{
for ( int j = 0; j < dim ; j++)
{
mat[i][j] = i * dim + j;
}
}
for (int i = 0; i < dim ; i++)
{
for ( int j = 0; j < dim ; j++)
{
cout << mat[i][j] << " " ;
}
cout << endl;
}
//释放内存时只需要操作一开始的一维数组指针就行
delete [] ptr;
return 0;
}
Running Results
The key to dynamic allocation of multi-dimensional arrays is to calculate the size of the entire array, and then allocate some memory. It should be noted that we cannot perform row-by-row allocation here, because the system does not necessarily return adjacent addresses when allocating memory in the heap, so the allocated array is not a real array. After the memory is allocated, all that needs to be done is to convert the ordinary pointer into a pointer to an n-1 dimensional array, so that the pointer will have information of these dimensions.