c++ copying arrays

Recommended Posts

pixelp    122
How do i copy one array to another? I've got two arrays(integers), array1[5] and array2[5]. Now i want to copy all the values from array1 to array2. How do i do that? [Edited by - pixelp on October 23, 2008 12:08:30 PM]

Share on other sites
SiCrane    11839
That depends on what language you're doing this in.

Share on other sites
Evil Steve    2017
for(int i=0; i<5; ++i)   array1[i] = array2[i];

Although that's with hard coding for the array length - there's no way to determine the length of the array unless you have it stored already.

However - this is somewhere that std::vector would be ideal...

Share on other sites
pixelp    122
Quote:
 Original post by SiCraneThat depends on what language you're doing this in.

oops.. i forgot to write that, its c++.

Quote:
 Original post by Evil Stevefor(int i=0; i<5; ++i) array1[i] = array2[i];Although that's with hard coding for the array length - there's no way to determine the length of the array unless you have it stored already.However - this is somewhere that std::vector would be ideal...

Yeah, that's kind of hard coding.
Isn't there any function like strcpy() but for integer arrays?

Share on other sites
ToohrVyk    1595
#include <algorithm>
std::copy(source, source+source_size, destination);

But boost::array or std::vector are saner ways of achieving this.

Share on other sites
stonemetal    288
There is memcpy.

memcpy(dest,src,sizeof(int)*srcLength);
It doesn't invoke copy constructors or anything it just shifts the bits, so it isn't a good general purpose solution but for ints it can be useful.

Share on other sites
mrbastard    1577
memcpy(array1, array2, sizeof(int) * 5);

or better:

std::copy(array1, array1+5, array2);

(EDIT: far too slow [smile])

Share on other sites
Antheus    2409
struct MyValues {  int values[5];};...MyValues a;a.values[0] = 1;a.values[1] = 2;...a.values[4] = 5;...MyValues b;...b = a;

Share on other sites
KulSeran    3267
IF you defined
int array[5];
int len = sizeof( array ) / sizeof( array[ 0 ] ); // = 5
NOTE this does not work if you have
int *array;
or otherwise let the array decay to a pointer though function calls/casts/etc.

far far far to slow, but i totally second std::copy() since it works on arrays of classes. (and on vectors, which you should use over arrays)

Share on other sites
pixelp    122
Thank you all! std::copy() is just what i was looking for.

Share on other sites
DevFred    840
Bjarne once said "most users of arrays are braindead". What are you using your arrays for? What is the meaning of those 5 numbers? Maybe a new data type that handles assgnment would be appropriate.

Share on other sites
pixelp    122
Nothing really, i'm just testing out different functions and such. It's not for any project.