Sign in to follow this  
pixelp

c++ copying arrays

Recommended Posts

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 this post


Link to post
Share on other sites

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 this post


Link to post
Share on other sites
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[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 this post


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


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

Share this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
struct MyValues {
int values[5];
};

...

MyValues a;
a.values[0] = 1;
a.values[1] = 2;
...
a.values[4] = 5;
...
MyValues b;
...
b = a;

Share this post


Link to post
Share on other sites
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 this post


Link to post
Share on other sites
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 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