How to initialize an array of 2D-arrays?
Asked Answered
R

2

14

I have an array of 2D-arrays. For example, it is like:

{{{0, 0, 1}, {1, 0, 0}}
{{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}}
{{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}}

But If I write

int [,][] arrays={{{0, 0, 1}, {1, 0, 0}}
                  {{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}}
                  {{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}};

the compiler will complain "; expected".

If I write

int [,][] arrays={new int[,] {{0, 0, 1}, {1, 0, 0}}
                  new int[,] {{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}}
                  new int[,] {{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}};

the compiler will complain

"A nested array initializer is expected".

So why does this happen and what is the correct way of initialization?

Rudiment answered 15/10, 2011 at 2:52 Comment(0)
E
25

You're trying to create jagged array. Your array has n rows so your first square should be [] not [,]. Element in each row (index of n) is 2D array so you need to use [,]. Finally, you can fix your problem by change int [,][] to int[][,].

int[][,] arrays = {
    new int[,] {{0, 0, 1}, {1, 0, 0}},
    new int[,] {{0, 0, 3}, {2, 1, 2}, {2, 2, 1}, {3, 0, 0}},
    new int[,] {{0, 0, 7}, {3, 2, 6}, {6, 2, 3}, {6, 3, 2}, {7, 0, 0}}
};
Enzyme answered 15/10, 2011 at 3:2 Comment(4)
I add new int[,][] at the beginning but the error is still there.Rudiment
Ahh, I see your problem, I have add correction code from your example.Enzyme
It works~ I thought int[,] is a type so the array of this type would be int[,][]. Why is it so?Rudiment
Add more explanation, hope this help. :)Enzyme
L
3

An array of 2d arrays is a 3d array:

int[, ,] array3D = new int[,,] { { { 1, 2, 3 } }, { { 4, 5, 6 } } };

Also see more at MSDN http://msdn.microsoft.com/en-us/library/2yd9wwz4(v=VS.90).aspx

Lollop answered 15/10, 2011 at 2:56 Comment(2)
But that makes fixed outermost index, which is clear from his question he wants not fixedDig
A 3d array also requires that all 3 indices be provided, resulting in an integer, whereas the asker wishes to index and get back a 2d array.Heelpiece

© 2022 - 2024 — McMap. All rights reserved.