Home > Back-end >  Can I copy the array element from source array to destination array reversing certain element with A
Can I copy the array element from source array to destination array reversing certain element with A

Time:06-15

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

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]

CodePudding user response:

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
  • Related