Home > database >  C# how to add an array to 2d array without it being linked?
C# how to add an array to 2d array without it being linked?

Time:02-25

My goal is to create a 2d array or list with default values of 0

Instead of creating the entire array an element at a time, I'm looking create an array and then copy it to multiple rows in an array.

I have a row: var row = new int[] {0,0,0,0};

I'm looking to add this to a 2day: arr[i] = row;

However, when I'm making a change to one of the rows, all of the rows change, this is because it's linked I believe. How can I copy an array to a 2d array without them being linked?

The same behavior is with a IList<list<int>>() too

Problem example: So if I update arr[0] = {1,0,0,0}

all rows would have the same values.

CodePudding user response:

Upon creation, .NET arrays are populated with default value for each member, so explicit zeroing an array of ints is redundant. As there is no example code in the question, I wrote a quick sample to illustrate the aforementioned:

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            int w = 4;
            int h = 5;
            var arr = new int[w][];
            for (int i = 0; i < w; i  )
            {
                arr[i] = new int[h];
            }

            Console.WriteLine("Initial state");
            Print(arr);

            arr[1][2] = 1;
            Console.WriteLine("After assignment");
            Print(arr);
        }

        static void Print(int[][] arr)
        {
            for (int i = 0; i < arr.GetLength(0); i  )
            {
                var arr2 = arr[i];
                for (int j = 0; j < arr2.GetLength(0); j  )
                {
                    Console.Write(arr2[j]   " ");
                }
                Console.WriteLine();
            }
        }
    }
}

and the output is this:

Initial state
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
After assignment
0 0 0 0 0
0 0 1 0 0
0 0 0 0 0
0 0 0 0 0

If this code is not similar to what you have, please add your version to the question.

  • Related