theonlygusti theonlygusti - 23 days ago 6
C# Question

How to assign to a jagged array?

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):


Answer

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] = '*';