Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Array.Copy work with multidimensional arrays?

This code works fine:

var newArray = new Rectangle[newHeight, newWidth];  for (int x = 0; x < newWidth; x++)     for (int y = 0; y < newHeight; y++)         newArray[y, x] = (x >= width) || (y >= height) ? Rectangle.Empty : tiles[y, x]; 

But I am not having much luck replacing it with Array.Copy. Basically, if the resized array is larger it just adds blank rectangles to the edges. If it is smaller then it should just cut off the edges.

When doing this:

Array.Copy(tiles, newArray, newWidth * newHeight);

It messes up the array and all of its contents become disordered and do not retain their original index. Maybe I'm just having a brainfart or something?

like image 549
Andrew Godfrey Avatar asked Sep 01 '11 02:09

Andrew Godfrey


People also ask

Does clone work with 2-D arrays?

1. Using clone() method. A simple solution is to use the clone() method to clone a 2-dimensional array in Java. The following solution uses a for loop to iterate over each row of the original array and then calls the clone() method to copy each row.

Does arrays copyOf work for 2-D arrays?

Using arraycopy() Method to Copy 2D Array in JavaWe can copy elements of any 2D array without iterating all the array elements with this method.

How do I copy a 2-D array into another?

Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.

Is a multidimensional array an array of arrays?

A multidimensional array is an array containing one or more arrays.


1 Answers

Yes. However, it doesn't work the way you are thinking it works. Rather, it thinks of each mutlidimensional array as a single-dimensional array (which is actually what they are in memory, it's just a trick that lets us place some structure on top of them to think of them as multidimensional) and then copies the single-dimensional structures. So if you have

1 2 3 4 5 6 

and want to copy it into

x x x x x x x x 

then it will think of the first array as

1 2 3 4 5 6 

and the second as

x x x x x x x x 

and the result will be

1 2 3 4 5 6 x x 

which will appear to you as

1 2 3 4 5 6 x x 

Got it?

like image 64
jason Avatar answered Sep 20 '22 15:09

jason