Why changing one array changes another array in C#?

爷,独闯天下 提交于 2019-12-01 23:54:37

In my mind your State definition is:

int[][] State;

Array is a reference type and when you copy an element from the State array you get a reference to the array from the first list and the both references map to the same int[] array. So when you change array stored at SubArray you use a link to the same array.

The simple fix is a copy of the source array

var SubState = State[0].ToArray();

That is because when you assign the array you pass its reference you are not making a copy of it. Look at the msdn link on the array copy method https://msdn.microsoft.com/en-us/library/System.Array.Copy(v=vs.110).aspx

int[] SubState = State [0]; is just another reference to the state array and so can be changed via it as well.

What you probably want to do, is create a separate array from the state array like

int[] substate = new int[state.GetLength(0)];
state.CopyTo(substate, 0);

You are not building a new one-dimensional array. You are simply creating a new reference to the first row of your two-dimensional array. If you actually want to build a new one-dimensional array, you have to iteratively copy the first row of your two-dimensional array.

Try:

int[] SubState = new int[States[0].length];
States[0].CopyTo(SubState, 0);

instead of

int[] SubState = State [0];

try

int[] SubState = new int[State[0].Length];
Array.Copy(State[0],Substate, Substate.Length)

So you are not simply assigning a new reference, but are actually copying the array correctly

Obviously your element at position 0 of State is an array of int which is a reference-type. Thus both SubState and State reference the same array which is why changes to any of their elements are reflected by both. To overcome this problem you may create a copy of your State-array and copy its values to SubState:

States.CopyTo(SubStates, 0);

EDIT: Thius assumes that SubStates was already initialized with the same size as States. e.g:

int[] SubStates = new int[States[0].Length];
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!