C # main question

why the item is not replaced

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 does not have the ref modifier, the array does not change. Is a copy of the link passed as a parameter to the right?

+6
c #
source share
4 answers

There is an error in your algorithm. For each i and j, your cycle swaps arr[i,j] and arr[j,i] twice.

For example, arr[3,1] is replaced by arr[1,3] once for i = 3, j = 1 and once for i = 1, j = 3. Thus, the original matrix. You must change j-loop to

 for (int j = 0; j < i; j++) 
+21
source share

The second arr.GetLength(0) should be arr.GetLength(1) . Because you want to use the second dimension.

+4
source share

Is a copy of the link passed as a parameter to the right?

Arrays are passed by reference.

 SwapArray(ref int[,] arr) 

Here you pass the link by reference (sorry for the tautology), this means that you can even reassign the link:

 arr = new int [10,20]; 
+1
source share

try it.

I changed the second cycle. ur actually replaces and reswapping again. so u stand where you 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; } } } 
+1
source share

All Articles