1

enter code here`I have a variable called curPos that stores two ints. I have a second variable prevPos that stores two ints.

So I have the following code

Console.WriteLine("{0}, {1}", curPos[0], curPos[1]); // 1, 25
Console.WriteLine("{0}, {1}", prevPos[0], prevPos[1]); // 1, 25
                    curPos[0]++;

Console.WriteLine("{0}, {1}", curPos[0], curPos[1]); // 2, 25
Console.WriteLine("{0}, {1}", prevPos[0], prevPos[1]); // 2, 25

how is this even possible and this is the exact code when I step line by line to the last line shown http://www.youtube.com/watch?v=qkPKm7xEhac&feature=youtu.be

2
  • How are curPos and prevPos created? They are referencing the same array. Commented Nov 24, 2012 at 11:31
  • @Lee public static int[] curPos = { 25, 25 }; public static int[] prevPos = { 25, 25 }; Commented Nov 24, 2012 at 15:24

2 Answers 2

4

Both variables are pointing at the same array. My guess is at some point in your code you have something like:

prevPos = curPos

When what you really want is

prevPos[0] = curPos[0]
prevPos[1] = curPos[1]
Sign up to request clarification or add additional context in comments.

2 Comments

just to show you what I mean I have uploaded a step by step walk trough of the code youtube.com/watch?v=qkPKm7xEhac&feature=youtu.be
you can also use the Array.Copy method
2

They might be two different variables but they are pointing to the same object.

A variable is a compile time construct that gives a name to a storage location. At runtime that storage location is what we generally refer to as an object.

if you say

var foo = int[]{0,1};
var bar = foo;

you have one array that you can access through two variables. It subsequently does not matter whether you do

foo[0]++;

or you type

bar[00]++;

the result is the same. The first integer in the array is incremented by one.

This holds true as long as the type of the variables is a reference type such as an array. If the type of the variables is a Value type such as int or Point then any assignment will create a copy

Point foo = new Point();
var bar = foo;

in this case bar and foo does not point to the same object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.