I’m trying to fill a 2D char array with characters form a char array
I have tried this code but not finding the problem
public void FillArray(char[,] array, char[] values)
{
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
for (int k = 0; k < values.Length; k++)
{
array[i, j] = values[k];
}
}
}
}
2
Answers
Here’s my best guess at what you want based on your comments:
Your first for loop is responsible for iteration over first dimension of array
(i)
It’s okay.Your second for loop is responsible for iteration over second dimension of array
(j)
. It’s okay.Your third loop is responsible for iteration over char values array
(k)
Here’s your bug.For a given set of values of
i
andj
which represents dimensions indexes of array, your function iterates through all positions ofvalues
array. So for eachk
valuei
andj
values remain unchanged. Therefore you sequentially put all the values ofvalues
array (k+1)times into the same cell of two dimension array, ultimately leaving it with value ofvalues[values.Length]
as it is the highest possible value ofk
in the most nested loop.I’d suggest solution similar to what @adv12 has proposed with slight modification as I am not sure if the
k
value would be 0 during first iteration of the nested for loop. It is also more readable IMO.