Reputation: 167
i have the following code:
static void Main(string[] args)
{
int m = 4, n = 5;
int[,] a = new int[m, n];
for (int i = 0; i < a.GetLength(0); i++)
for (int j = 0; j < a.GetLength(1); j++)
a[i, j] = random.Next(10);
VypisMatici(a);
int[,] a0 = a;
Console.WriteLine("Chessboard: ");
for (int i = 0; i < a0.GetLength(0); i++)
{
for (int j = 0; j < a0.GetLength(1); j++)
{
if (((j % 2 == 0) && (i % 2 == 0) && (a0[i, j] % 2 == 0)) || ((j % 2 != 0) && (i % 2 != 0) && (a0[i, j] % 2 == 0)) || ((j % 2 != 0) && (i % 2 == 0) && (a0[i, j] % 2 != 0)) || ((j % 2 == 0) && (i % 2 != 0) && (a0[i, j] % 2 != 0)))
{
a0[i, j]++;
}
}
}
Console.WriteLine("---------");
for (int i = 0; i < a0.GetLength(0); i++)
{
for (int j = 0; j < a0.GetLength(1); j++)
Console.Write("{0,2}, ", a0[i, j]);
Console.WriteLine();
}
Console.WriteLine("Vypsání v opačném pořadí: ");
int[,] a1 = new int[a.GetLength(0), a.GetLength(1)];
for (int i = 0; i < a1.GetLength(0); i++)
{
for (int j = 0; j < a1.GetLength(1); j++)
{
a1[i, a1.GetLength(1) - (j + 1)] = a[i, j];
}
}
VypisMatici(a1);
Console.WriteLine("Prohození prvků na řádcích: ");
int temp;
int[,] a2 = a;
for (int i = 0; i < a2.GetLength(0); i +=2)
{
for (int j = 0; j < a2.GetLength(1); j++)
{
if (a2.GetLength(0) - 1 > i)
{
temp = a2[i, j];
a2[i, j] = a2[i + 1, j];
a2[i + 1, j] = temp;
}
}
}
VypisMatici(a2);
Console.ReadLine();
}
static void VypisMatici(int[,] matice)
{
// Vypsání matice
for (int i = 0; i < matice.GetLength(0); i++)
{
for (int j = 0; j < matice.GetLength(1); j++)
Console.Write("{0,2}, ", matice[i, j]);
Console.WriteLine();
}
Console.WriteLine();
}
}
The important code is „chessboard“ and above. The chessboard should increase some elements of array so i get array, which looks like a chessboard - odd numbers will be white square and even numbers will be black square. My problem is, that array a is after the chessboard loop same as a0. I am wondering why. (sorry for strings in czech language - actually the part in czech is not important in this problem). Sorry for my bad english. Thanks for help.
Upvotes: 0
Views: 57
Reputation: 1613
In the line int[,] a0 = a;
, you are not copying the array, but giving it a second name (reference) to the same object in memory. So when you modify a0, a is also changed.
Upvotes: 2