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?
Anonymous User
05-Oct-2013You now have two variables that refer to the same array