Trying to understand multidimensional arrays in D

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 26 03:15:50 PST 2017


On Thursday, January 26, 2017 05:44:04 Profile Anaysis via Digitalmars-d-
learn wrote:
> I am using static arrays because the size of the matrix is fixed.
> I need to allocate them though because that is what my
> matrix_history contains.

If I understood correctly, you want a dynamic array of static arrays where
the static array is therefore an entry in your "matrix history." That does
not require that you allocate a static array. It just requires that you
allocate the dynamic array of static arrays. For instance, if you had an
integer instead of a matrix, you would have something like

int[] arr;

and when you appended to it, you would just append the value. e.g.

arr ~= 42;
arr ~= 77;
arr ~= 9;

No allocation of the values is required. The dynamic array may very well do
some reallocating to fit the new values (depending on its current capacity),
but the values themselves are not allocated. So, if you have a dynamic array
of static arrays

int[4][4][] arr;

then you just append each static array. e.g.

int[4][4] value;
// fill in value...

arr ~= value;

or

arr ~= [[9, 9, 9, 9], [7, 7, 7, 7], [2, 2, 2, 2], [3, 3, 3, 3]];

Again. You're not allocating the values that you're appending at all. At
most, the dynamic array ends up being reallocated to make room for more
elements.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list