It's because arrays are references types, and .dup is a strictly
shallow copy, so you're getting two outer arrays that reference
the same set of inner arrays. You'll have to duplicated each of
the inner arrays yourself if you need to make a deep copy.

On Friday, 8 May 2015 at 02:15:38 UTC, Dennis Ritchie wrote:
Hi,
Should the method .dup work with multidimensional arrays for copying?

-----
import std.stdio;

void main() {

        auto a = [1, 2, 3];
        auto b = a.dup;

        b[] *= 2;
        writeln("a = ", a); // [1, 2, 3] // OK
        writeln("b = ", b); // [2, 4, 6] // OK


        auto c = [[[1, 2, 3], [4, 5, 6, 7, 8]],
                  [[9, 10], [11, 12, 13]]];

        auto d = c.dup;

        writeln("d[0][1][1 .. $ - 1] = ",
                 d[0][1][1 .. $ - 1]);

        d[0][1][1 .. $ - 1] *= 3;

        writeln("c = ", c);
        // [[[1, 2, 3], [4, 15, 18, 21, 8]],
        //  [[9, 10], [11, 12, 13]]] // wrong
        writeln("d = ", d);
        // [[[1, 2, 3], [4, 15, 18, 21, 8]],
        //  [[9, 10], [11, 12, 13]]] // OK
}
-----
http://ideone.com/Ddtm47

I thought the slice of the array c[0][1][1 .. $ - 1] = [5, 6, 7] not had to change to [15, 18, 21] by multiplying by 3.

Reply via email to