Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I copy the array element from source array to destination array reversing certain element with Array.Copy() in c#

I have the following code where elements of SourceArray are being copied to 2 separate Arrays namely DestArray1 and DestArray2.

output:

  • DestArray1 will have the first 4 elements of SourceArray but in the reverse form [4 3 2 1]
  • DestArray2 will have the last 4 elements of SourceArray. [5 6 7 8]

I want to replace the for loop with Array.Copy() method

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if not reversed then Array.Copy() works kind of fine except for the last element, but to copy with reverse, it seems the Array.Copy doesn’t work or I am not able to implement it.

int i, j;
int bytelength =8;
int halfbytelength = 4;

byte[] SourceArray = new byte[]{ 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] DestArray1 = new byte[4];
byte[] DestArray2 = new byte[4];

for (i = halfbytelength - 1, j = 0; i >= 0; i -= 1, j++)
 {
   DestArray1[j] = SourceArray[i];
 }
for (i = halfbytelength; i < bytelength; i += 1)
{
  DestArray2[i - halfbytelength] = SourceArray[i];
}

I tried following the code but the results are not as expected as seen in(Results:), is there a way to do it?

Array.Copy(SourceArray, 0, DestArray1, 3, 0);
Array.Copy(SourceArray, 4, DestArray2, 0, 3);

Result:
DestArray1: [0 0 0 0]
DestArray2: [5 6 7 0]

>Solution :

First array.

To reverse array you can just call Array.Reverse() after copying:

Array.Copy(SourceArray, 0, DestArray1, 0, 4);
Array.Reverse(DestArray1);

Second array.

if not reversed then Array.Copy() works kind of fine except for the
last element

Because you pass invalid count of elements to copy (last parameter):

Array.Copy(SourceArray, 4, DestArray2, 0, 3); // 3 - elements count, not an index

Simply replace 3 with 4:

Array.Copy(SourceArray, 4, DestArray2, 0, 4); // 4 and it will copy including the last element
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading