I've got Function1 where user inputs data in array1. I must make array2 in Function2 to be equal to array1 from Function1.
How do I "tell it" that it should use array1 from Function1?
I've tried
array2[50] = array1[50];
but of course that is not working.
-
I would suggest this -> devx.com/tips/Tip/13291Oliver– Oliver2012年05月07日 09:32:31 +00:00Commented May 7, 2012 at 9:32
-
What is your goal ? Do you only need the values of array1 to be read by Function2 ? do you need to modify them ? Did you consider using something like a vector instead of an array ?Dinaiz– Dinaiz2012年05月07日 10:58:33 +00:00Commented May 7, 2012 at 10:58
-
1Do you really ned to copy the array? Why not just use the same array?johnsyweb– johnsyweb2012年05月07日 10:58:35 +00:00Commented May 7, 2012 at 10:58
-
I needed to copy the array and modify the copy. I have yet to study how vectors work, so I have no idea how to use them. Thanks though.A Petrov– A Petrov2012年05月07日 11:56:15 +00:00Commented May 7, 2012 at 11:56
-
Vectors work like "smart arrays". Besides automatic resizing and bounds checking, you can simply do vector2=vector1 and vector2 will be an independant copy of vector 1Dinaiz– Dinaiz2012年05月08日 20:09:07 +00:00Commented May 8, 2012 at 20:09
3 Answers 3
You need to copy array1 elementwise into array2, e.g.
for (unsigned i=0; i<array1_size; ++i) {
array2[i] = array1[i];
}
You can also use std::copy from the algorithm header.
std::copy(array1, array1 + array1_size, array2);
For both approaches you need to know the number of elements in array1 (array1_size in the examples). Also, array2 needs to be at least as big as array1.
Comments
Iterate over all elements in one array and assign them to the second one.
Comments
memcpy(second_array, first_array, sizeof(second_array));
[Original Source Site][http://www.devx.com/tips/Tip/13291]
4 Comments
std::copy is as fast as memcpy but much safer.