c++ copying arrays

Started by
10 comments, last by pixelp 15 years, 6 months ago
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]
Advertisement
That depends on what language you're doing this in.
for(int i=0; i<5; ++i)   array1 = array2;

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...
Quote:Original post by SiCrane
That depends on what language you're doing this in.

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

Quote:Original post by Evil Steve
for(int i=0; i<5; ++i)   array1 = array2;

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?
#include <algorithm>
std::copy(source, source+source_size, destination);

But boost::array or std::vector are saner ways of achieving this.
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.
memcpy(array1, array2, sizeof(int) * 5);

or better:

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

(EDIT: far too slow [smile])
[size="1"]
struct MyValues {  int values[5];};...MyValues a;a.values[0] = 1;a.values[1] = 2;...a.values[4] = 5;...MyValues b;...b = a;
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)
Thank you all! std::copy() is just what i was looking for.

This topic is closed to new replies.

Advertisement