-2

I have a function that gets called on a two dimensional array "a" and alters the array. However, it also alters any array that was previously assigned to "a", before even calling the function. I'm not sure if I understand why!

char[][] copy;

copy = a; // a is a also a two dimensional char array

DFSfunction(a); //DFSfunction alters values of a

So after DFSfunction is called, values of "copy" is also altered. How can I keep a copy of the original "a"?

Thank you!

Jonas W
  • 3,200
  • 1
  • 31
  • 44
Nila
  • 1
  • 4
  • 1
    Clone the array before passing it in. – mjwills Apr 28 '21 at 04:57
  • do a [deep copy](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) which is achieved wit h`Array.Clone` https://www.geeksforgeeks.org/shallow-copy-and-deep-copy-in-c-sharp/ – phuclv Apr 28 '21 at 05:03
  • 2
    Technically clone does a shallow copy - but it will be sufficient for chars @phuclv. – mjwills Apr 28 '21 at 05:09

1 Answers1

2

Arrays are mutable in C# so if you change a in your example it will have an effect on copy as well, since they still have the same reference

So when you wrote

copy = a

copy is just pointing to the same a array.

To solve this you can use Array.Copy..

In your example it can look something like this :

char[][] copy;
char[][] a;

Array.Copy(a, copy, a.Length);

You can also use Array.Clone :

var copy = (char[][])a.Clone();
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Jonas W
  • 3,200
  • 1
  • 31
  • 44