首先,您正在做的是将 1 添加到一维数组的不同插槽中。
这是您的代码的注释版本:
int *a = new int[m*n]; // declares a pointer a, that points to a newly
// allocated space on the heap, for an array of size m*n.
for( int i = 0 ; i < m ; i++) // loop through m number of times
for ( int j = 0 ; j < n ; j++) // loop through n number of times PER m
a[i*n + j] = 1; // assigns 1 to a spot [i*n + j]
这就是您制作动态二维数组的方式(换句话说,指向数组的指针数组):
const int sizeX = 10;
const int sizeY = 5;
int** arrayOfPointers = new int*[sizeX];
for(int i = 0; i < sizeX; i++)
arrayOfPointers[i] = new int[sizeY];
然后,您可以使用双循环(未测试)向该数组添加多个元素:
for(int i = 0 ; i < sizeY ; i++) // loop through all the rows
for (int j = 0 ; j < sizeX ; j++) // loop through all columns for row i
arrayOfPointers[i][j] = i*j; // assigns i*j to a spot at row i, column j
这是打印二维数组内容的方法:
for(int i = 0 ; i < sizeY ; i++) {
for (int j = 0 ; j < sizeX ; j++)
cout << arrayOfPointers[i][j];
cout << endl; // go to the next line when the row is finished
}