How to assign to a jagged array?

旧巷老猫 提交于 2020-01-14 08:45:12

问题


I am writing a short program which will eventually play connect four.

Here it is so far, pastebin

There is one part which isn't working. I have a jagged array declared on line 16:

char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray();

Which I think looks like this:

-------
-------
-------
-------
-------
-------
-------

when I do this board[5][2] = '*' I get

--*----
--*----
--*----
--*----
--*----
--*----
--*----

instead of what I'd like:

-------
-------
-------
-------
-------
--*----
-------

How it runs at the moment (output should only have one asterisk):


回答1:


You are creating your jagged array in wrong way !

char[][] board = Enumerable.Repeat(Enumerable.Repeat('-', 7).ToArray(), 7).ToArray();

Enumerable.Repeat will create a sequence that contains one repeated value. So you will create an char[][] in which every array will point to same reference. In this case when you change one of the arrays you will change all of them.

You need to create the jagged array this way and array[5][2] will only change the 5th array :

char[][] array = Enumerable.Range(0, 7).Select(i => Enumerable.Repeat('-', 7).ToArray()).ToArray();

array[5][2] = '*';


来源:https://stackoverflow.com/questions/40644966/how-to-assign-to-a-jagged-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!