如何初始化二维数组的数组?
我有一个二维数组的数组。例如,它就像:
{{{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}}}
但是如果我写,
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}}};
编译器会抱怨“;预期”。
如果我这样写,
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}}};
编译器会抱怨
“需要一个嵌套数组初始值设定项”。
那么为什么会发生这种情况以及正确的初始化方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试创建锯齿状数组。您的数组有 n 行,因此您的第一个方块应该是 [] 而不是 [,]。每行中的元素(
n
的索引)是二维数组,因此您需要使用[,]
。最后,您可以通过将 int[,][]
更改为int[][,]
来解决您的问题。You're trying to create jagged array. Your array has
n
rows so your first square should be [] not [,]. Element in each row (index ofn
) is 2D array so you need to use[,]
. Finally, you can fix your problem by change int[,][]
toint[][,]
.2d 数组的数组是 3d 数组:
另请参阅 MSDN 获取更多信息
http://msdn.microsoft.com/en-我们/library/2yd9wwz4(v=VS.90).aspx
An array of 2d arrays is a 3d array:
Also see more at MSDN
http://msdn.microsoft.com/en-us/library/2yd9wwz4(v=VS.90).aspx