Reputation: 4314
why doesn't the element get swapped
public static void SwapArray(int[,] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(0); j++)
{
int temp = arr[i, j];
arr[i, j] = arr[j, i];
arr[j, i] = temp;
}
}
}
even if the parameter is without a ref modifier the array doesn't change. a copy of the reference is passed as a parameter right?
Upvotes: 6
Views: 316
Reputation: 5123
a copy of the reference is passed as a parameter right?
Arrays are passed by reference.
SwapArray(ref int[,] arr)
Here you are passing a reference by reference (sorry, for tautology), this means, that you can even reassign a reference:
arr = new int [10,20];
Upvotes: 1
Reputation: 1641
try this.
I have changed the second for loop. u r actually swapping and again reswapping. so u stand where u were.
public static void SwapArray(int[,] arr)
{
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = i+1; j < arr.GetLength(0); j++)
{
int temp = arr[i, j];
arr[i, j] = arr[j, i];
arr[j, i] = temp;
}
}
}
Upvotes: 1
Reputation: 885
The second arr.GetLength(0)
should be arr.GetLength(1)
. Because you want to use the 2nd dimension.
Upvotes: 4
Reputation: 25593
There is an error in your algorithm. For every i and j, your loop swaps arr[i,j]
and arr[j,i]
twice.
For example arr[3,1]
gets swapped with arr[1,3]
once for i=3, j=1 and once for i=1, j=3. So the result is the original matrix. You should change the j-loop to
for (int j = 0; j < i; j++)
Upvotes: 21