Good evening. Faced a problem: one function stores the value of the variable mas.values ​​(int [,]), which can be used in other functions, and the other function does not save the value of the variable mas.average (float). F-ii declared the same way. What is the problem?

all code: tyk

ps just started learning C # yesterday

this is a working function

static public void Sort(ARRAY mas) //сортировка { int temp; //"буферная" переменная for (int m = 0; m < mas.size1 * mas.size2; m++) for (int k = 0; k < mas.size1; k++) for (int l = 0; l < mas.size2 - 1; l++) { if (mas.values[k, l] > mas.values[k, l + 1]) { temp = mas.values[k, l]; mas.values[k, l] = mas.values[k, l + 1]; mas.values[k, l + 1] = temp; } } } 

it doesn't want to keep the value of mas.average

  static public void Arg(ARRAY mas) // среднее значение { int sum = 0; for (int i = 0; i < mas.size1; i++) { for (int j = 0; j < mas.size2; j++) sum += mas.values[i, j]; } Console.WriteLine("sum =" + sum); mas.average = sum / mas.size1 * mas.size2; Console.WriteLine(mas.average + "<-arg"); } 
  • What does it mean does not save? - adrug
  • when using variables in other f-mas, mas.value has the same value that it received in f-ii above, and the variable mas.average is equal to 1 (first set by the constructor) after exiting f-ii below. - ImmRaytal
  • 3
    Structures in functions are passed by value, not by reference, so you have variables and do not change. Only in the first case the link to the array is copied by value, therefore it works, and in the second the variable average is not a reference. - Alex Krass
  • 2
    @ Andrei Comrade Alex Krass is right. And in your case, the struct ARRAY is easier to change to class ARRAY , then the program will work. Or it is possible to transfer all functions by reference, that is, instead of (ARRAY mas) in functions, write (ref ARRAY mas) . - John
  • one
    More material on this topic. When passed as a parameter whose type is "struct", its copy will be transferred full, but since one of its fields is an array (reference type), then it will remain the same. - adrug

1 answer 1

Thanks for the advice, the task was solved by passing mas by reference, that is:

It was

  static public void Arg(ARRAY mas) Arg(mas); 

It became

  static public void Arg(ref ARRAY mas) Arg(ref mas);