Sign in to follow this  
EvilNando

[.net] How to copy arrays?

Recommended Posts

It seems that this one is always giving me troubles. Im trying to copy an array I want a copy not a reference so Im doing aux = myarray.Clone(); but whenever I want to retrieve my aux value it returns the current value for myarray?? I really dont get it any tips for this one?

Share this post


Link to post
Share on other sites
In laymens terms, if you want to copy an array you need to make two arrays and allocate memory
for both of them, this is what keeps them seperate. Then you do the copies. There are calls you can make that let you do this in one call, but if you want to explicitly ensure the copy takes place then explicitly do a new array1, new array2 ... for (){ array2[x] = array1[x]} ... might not be the most efficient, but you know it works.

Hope that helps.

Share this post


Link to post
Share on other sites
I'd recommend just using what is already available for array copying:

class Program
{
static void Main(string[] args)
{
byte[] a1 = new byte[] { 1, 5, 2, 34, 1, 2, 3 };
byte[] a2 = new byte[a1.Length];

a1.CopyTo(a2, 0);

Array.Copy(a1, a2, a1.Length);

Buffer.BlockCopy(a1, 0, a2, 0, a1.Length);

// etc...
}
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this