Thiago
Thiago

Reputation: 335

How to copy an array?

I am trying to create a temporary array

Stack<Point[]> v = new Stack<Point[]>();
Point[] c= new Point[4];

then store it in a stack

v.Push(c);

but every time I try to modify the array, it also modify every instance inside the stack.

c[state] = mouse;

Is there a way to copy it into the stack?

Upvotes: 0

Views: 162

Answers (3)

user3188639
user3188639

Reputation:

Yes. Your stack only keeps the reference to the array. You have to create a copy of the array.

Stack<Point[]> v = new Stack<Point[]>();
Point[] c = new Point[4];
v.Push(c);

c[0] = new Point(5, 5);
Point[] cc = new Point[c.Length];
Array.Copy(c, cc, c.Length);
cc[0] = cc[0];

c[0].X = 20;
c[0].Y = 20;
var cx = v.Pop();

Console.WriteLine(c[0]);
Console.WriteLine(cx[0]);
Console.WriteLine(cc[0]);

EDIT: the result:

{X=20,Y=20}
{X=20,Y=20}
{X=5,Y=5}

Upvotes: 1

Thiago
Thiago

Reputation: 335

When you say that:

int[] arr1=arr2; 

It does not simply copy the data of one variable to another, it store a reference instead.

The solution to my problem is:

v.Push(new Point[4]);
Point[] c = v.Last();

Here i am referring 'c' to the last variable of my stack.

What was happening before is that i was referring every single variable of my stack to 'c'.

Upvotes: 0

D-Shih
D-Shih

Reputation: 46219

Because arrays are references type you use the same instance, so every time I modify the array, it also modifies every instance inside the stack.

I would create a new instance array to Stack instead of c, It can split two array.

Stack<Point[]> v = new Stack<Point[]>();
Point[] c = new Point[4];
v.Push(new Point[4]);
c[0] = new Point(1, 1);

if there are some data in c Point[], you can try to use CopyTo to copy the data to another array.

Stack<Point[]> v = new Stack<Point[]>();
Point[] c = new Point[4];

Point[] pushArr = new Point[c.Length];
c.CopyTo(pushArr, 0);
v.Push(pushArr);

Upvotes: 2

Related Questions