0

I have a multidimensional array with values. I use two for loops to loop through each item and add a value to them. While in the array they return the correct value, but when it exits and I get the value it is completely different. For example:

  • Before loop: [[1,1],[2,2],[3,3]]
  • During loop: [[2,2],[3,3],[4,4]]
  • After loop [[50,50][65,65][90,90]]

It just seems to randomly change.

int[,] squareB = baseSquare;
int[,] squareC = baseSquare;
int[,] squareD = baseSquare;
Console.WriteLine("{0}", squareB[0, 1]);
for (int x = 0; x < sub; ++x)
{
     for (int y = 0; y < sub; ++y)
     {
          squareB[x, y] += 9;
          Console.WriteLine("{0}", squareB[x, y]);
          squareC[x, y] += 18;
          squareD[x, y] += 27;
     }
}
Console.WriteLine("{0}", squareB[0, 1]);
Aurange
  • 943
  • 2
  • 9
  • 23

1 Answers1

4

You're modifying the exact same array tree times at every single loop iteration:

      squareB[x, y] += 9;
      squareC[x, y] += 18;
      squareD[x, y] += 27;

These all change the exact same value.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263