常规静态分配数组如下所示,可以使用以下公式进行访问:
const int N = 3;
const int M = 3;
int a1[N][M] = { {0,1,2}, {3,4,5}, {6,7,8} };
int x = a1[1][2]; // x = 5
int y = *(a1+2+N*1); // y = 5, this is what [] operator is doing in the background
Run Code Online (Sandbox Code Playgroud)
数组是连续的内存区域。在动态数组分配的情况下看起来有所不同,而是有指向数组的指针数组:
int** a2 = new int*[N];
for (int i = 0; i < N; i++)
a2[i] = new int[M];
//Assignment of values as in previous example
int x = a2[1][2];
int y = *(*(a2+1))+2); // …Run Code Online (Sandbox Code Playgroud) c c++ pointer-arithmetic multidimensional-array implicit-conversion