Home > DeveloperSection > Forums > Automatically Copy one to array to another array
Brad Pitt
Brad Pitt

Total Post:61

Points:429
Posted on    October-05-2013 3:39 AM

 C# C# 
Ratings:


 1 Reply(s)
 651  View(s)
Rate this:

I wrote this code that fills an array and a second array copies the first. I change some numbers in the second array, but when I output both arrays, the first one has also changed. This is my code:

        int[] array1 = new int[5];
        int[] array2 = new int[5];
        int temp;
        for (int i = 0; i < array1.Length; i++)
        {
            array1[i] = i;
        }
        array2 = array1;
        temp = array2[2];
        array2[2] = array2[4];
        array2[4] = temp;
        for (int i = 0; i < array1.Length; i++)
        {
            richTextBox1.Text += array1[i].ToString() + " ";
        }
        for (int i = 0; i < array2.Length; i++)
        {
            richTextBox1.Text += array2[i].ToString() + " ";
        }

Can someone explain to me why the output is 0 1 4 3 2 0 1 4 3 2 instead of 0 1 2 3 4 0 1 4 3 2?



Garry Winogrand
Garry Winogrand

Total Post:24

Points:168
Posted on    October-05-2013 4:25 AM

array2 = array1;

You now have two variables that refer to the same array


Don't want to miss updates? Please click the below button!

Follow MindStick