上面的答案都适用于分配一维 int 数组。无论如何,我想补充一点,对于通常定义为 int[][] matrix = {{1,2}, {3,4}} 的多维数组,也可以这样做。
关键是您将所有元素动态存储在一个数组中,并利用数组是内存中连续块的事实(请参阅here 以了解“块”的说明),这意味着您可以“切片” “穿越维度的你自己。您可以在下面看到一个二维数组的示例。
您可以在 SO 上找到有关此主题的讨论 here。
/*Defining a 2d-matrix.*/
struct Matrix {
int rows, columns;
int* matrix;
Matrix(int rows, int columns) : rows(rows), columns(columns) {
// Keep in mind that arrays cannot be generated during runtime
// since the compiler needs to know the size to allocate in memory.
// Thus, use dynamic memory and keep in mind to delete it!
// This only uses a single array since "new" cannot create
// multidimensional arrays by default. Thus, everything is
// written in a single memory-block and accessed via getElement().
matrix = new int[columns * rows];
}
~Matrix() {
// Release the memory after destroying the Matrix-object
delete matrix;
}
/*Access the element at position [r]ow and [c]olumn.*/
int getElement(int r, int c) {
// matrix[c][r] is rewritten as matrix[column + columns * rows]
// -> matrix <=> Single memory block
return matrix[c + columns * r];
}
/*Set the element at position [r]ow and [c]olumn with given [val]ue.*/
void setElement(int r, int c, int val) {
matrix[c + columns * r] = val;
}
};
填充此类Matrix-object 的示例如下:
/*Initialize the matrix with the continuous numbers 0..N*/
void Matrix::initDummyMatrix(){
int counter = 0;
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < columns; ++col) {
setElement(row, col, counter++);
}
}
}