You can allocate one big block and use it appropriately, something like this:
double* A = new double[m*n];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
A[i*n+j] = <my_value>;
}
}
Instead of using new
, you can use malloc
- there is no much difference, except that new
must be released with delete
, and malloc()
released with free()
.
UPDATE1:
You can create "true" 2d array as follows:
double** A = new double*[m];
double* B = new double[m*n];
for (int i=0; i<m; i++) {
A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
A[i][j] = <my_value>;
}
}
Just be sure to release both A
and B
in the end.
UPDATE2:
By popular request, this is how you can create "true" 3-dimensional array (with dimensions m
x n
x o
):
double*** A = new double**[m];
double** B = new double*[m*n];
double* C = new double[m*n*o];
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
B[n*i+j] = C + (n*i+j)*o;
}
A[i] = B + n*i;
}
for (int i=0; i<m; i++) {
for (int j=0; j<n; j++) {
for (int k=0; k<o; k++) {
A[i][j][k] = <my_value>;
}
}
}
This uses 2 relatively small "index" arrays A
and B
, and data array C
. As usual, all three should be released after use.
Extending this for more dimensions is left as an exercise for the reader.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…