Trying to understand multidimensional arrays in D
Profile Anaysis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jan 25 17:47:53 PST 2017
I'm a bit confused by how D does arrays.
I would like to create a array of matrices but I do not seem to
get the correct behavior:
int[][4][4] matrix_history;
What I would like is to have a 4x4 matrix and have a history of
it. Just n 4x4 matrices but each matrix is a fixed size but there
can be an arbitrary(dynamic) number.
I would like, for example,
matrix_history[0] to be the first 4x4 matrix,
matrix_history[1] to be the second 4x4 matrix,
...
and I would, in fact, like to be able to append a matrix like
matrix_history ~= some_4x4matrix.
I try to assign like
matrix_history[total-1] = new int[][](8,8);
or append
matrix_history ~= new int[][](4,4);
but the append fails with
Error: cannot append type int[][] to type int[][4][4]
which is confusing because the type per entry in the matrix
history is of type int[][].
e.g., I could wrap the int[][] in a struct and then just have a
singular array of these matrices and, to me, the logic should be
the same. e.g.,
struct matrix
{
int[4][4] data;
}
then
matrix[] matrix_history.
and
matrix_history ~= new matrix;
so, the logic should be the same between two. This method works
but the more direct method doesn't seem to.
If I do
auto x = matrix_history[0];
x is not a int[4][4] but of type int[4](as reported by the
debugger), which is very confusing.
it seems that the way D indexes multidimensional arrays is not
logical nor consistent from my perspective.
auto x = matrix_history[0] returns an array of size 4.
auto x = matrix_history[0][0] returns an 2d array of size 4x4.
auto x = matrix_history[0][0][0] returns an int(as expected).
does this mean that have
int[][4][4] matrix_history;
backwards?
int[4][4][] matrix_history;
this creates even a more set of problems.
I guess I will have to revert to wrapping the matrix in a struct
to get the natural extension of single arrays unless someone can
clue me in on what is going on.
More information about the Digitalmars-d-learn
mailing list