On Wednesday, 12 March 2014 at 02:14:45 UTC, bearophile wrote:
ed:

I am trying to convert a 1D array to a 2D array

If you have a dynamic array (1D), you can convert it to a dynamic array of dynamic arrays (2D) using chunks:


void main() {
    import std.stdio, std.range, std.algorithm;

    int[] a = [1, 2, 3, 4, 5, 6];
    int[][] b = a.chunks(2).array;
    b.writeln;
}


Output:

[[1, 2], [3, 4], [5, 6]]

Your problems are caused by mixing fixed-size arrays (that are values, allocated in-place), with dynamic arrays (that are little length+pointer structs that often point to heap-allocated memory).

Bye,
bearophile

Thanks for explaining this, it makes sense what you said. But I'm still not sure why my original Example 1 worked.

~~~
// This works OK and converts long[4] to int[] then implicitly to int[2][2]
long[4] a=[1,2,3,4];
int[2][2] b = to!(int[])(a);

// Why does this not work the same way?
long[4] a=[1,2,3,4];
int[2][2] b;
b = to!(int[])(a);
~~~

My understanding of your explanation is that it shouldn't work.


Cheers,
ed

Reply via email to