How to initialize an array of 2D-arrays?

ziyuang picture ziyuang · Oct 15, 2011 · Viewed 23.6k times · Source

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?

Answer

Ekk picture Ekk · Oct 15, 2011

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}}
};