skip to Main Content

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


  1. Here’s my best guess at what you want based on your comments:

    int k = 0;
    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++)
            {
                array[i, j] = values[k++];
                if (k >= values.Length)
                {
                    k = 0;
                }
            }
        }
    }
    
    Login or Signup to reply.
  2. 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 and j which represents dimensions indexes of array, your function iterates through all positions of values array. So for each k value i and j values remain unchanged. Therefore you sequentially put all the values of values array (k+1)times into the same cell of two dimension array, ultimately leaving it with value of values[values.Length] as it is the highest possible value of k 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.

    int k = 0;
    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++)
            {
                array[i, j] = values[k];
                k++
                if (k >= values.Length)
                {
                    k = 0;
                }
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search