2

Regarding passing arrays to functions and then manipulating the array contents (Array.Reverse) and then using pointers I extract the values from the array. But before jumping into the function, here is what I do;

byte[] arrayA = OriginalArray
byte[] arrayB = arrayA;

manipulate(OriginalArray);

And the function abstracted, looks like this

manipulateArray(byte[] OriginalArray) // This is unsafe
{
   // Unsafe code that keeps a pointer to OriginalArray
  // Array reverse 
  // Value extraction via pointer
}

After doing so, to my surprise what I am getting is that arrayB now "has" its values manipulated as if I had passed it to the function! Unless I missed something, I am pretty sure that I have not done something wrong. I made sure that the function is called after the arrayA and arrayB assignments.

Need guidance on this. Thanks

3 Answers 3

3

If you want arrayB to retain the same values you'll need to make a copy of arrayA. Both arrayA and arrayB are pointing to the same reference in your example.

Here's a quick example to illustrate the point:

byte[] originalArray = new byte[] { 1, 2, 3 };
byte[] arrayA = originalArray;
byte[] arrayB = arrayA;

//Both arrays point to the same reference, changes to arrayA
//or arrayB will affect both variables
arrayA[0] = 3;
arrayB[2] = 1;
//Both will output 3, 2, 1
Console.WriteLine("{0} {1} {2}", arrayA[0], arrayA[1], arrayA[2]);
Console.WriteLine("{0} {1} {2}", arrayB[0], arrayB[1], arrayB[2]);

//Copy array - both arrays point to different references
//Actions on arrayA will not affect arrayB
arrayB = new byte[arrayA.Length];
arrayA.CopyTo(arrayB, 0);
arrayA[0] = 1;
arrayA[2] = 3;
//First will output 1,2,3, second will output 3, 2, 1
Console.WriteLine("{0} {1} {2}", arrayA[0], arrayA[1], arrayA[2]);
Console.WriteLine("{0} {1} {2}", arrayB[0], arrayB[1], arrayB[2]);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the detailed answer. Chose your's as correct as you were the first in many who gave the same answer. Nevertheless, cheers!
3
byte[] arrayB = arrayA;

Does not cause copying of arrayA, only of its reference - you ARE passing arrayB to the method.

Comments

3

Arrays in C# are reference types. Both arrayA and arrayB are just references (sort-of pointers, but not really) to the same array instance on the heap. If you want to provide copies, you have to explicitly CopyTo() the array contents.

arrayA.CopyTo(arrayB, 0);
//or
Array.Copy(arrayA, arrayB, arrayB.Length);

Comments

Your Answer

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