[.net] How to copy arrays?
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?
A copy of an array is not an array of copies. Both arrays (the original and the copy) will contain the same objects, because cloning is shallow. So, clone the contents as well.
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.
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.
oh ok ill go the for() route
... maybe its time to toy with that parallel.for() ive seen somewhere on the net
... maybe its time to toy with that parallel.for() ive seen somewhere on the net
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... }}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement