-
Copying Arrays
What is the correct way to copy an array to another array in C++? Currently, I am just saying: array1=array2;
I have a feeling there is a problem with this, because there are some compilers which are complaining and some which aren't. Is the correct way just to run a for loop and copy each value one by one?
Thanks, appreciate it.
Nimit
-
That seems a sensible way of copying arrays to me. As long as you stay within the bounds of the arrays, there shouldn't be any problems.
-
This is logical for me...why wouldn't it be correct?
Code:
for(int i = 0; i < arraysize; i ++)
array2[i] = array1[i];
-
You could use memcpy, i.e.
void *memcpy(void *dest, const void *src, size_t n);
Where n is the number of bytes to be copied.
-
You can encapsulate it in a class or struct or union and just let the assignment operator do it for you.
IE:
Code:
struct Array
{
int Data[5];
};
// Then you can do:
Array A, B;
/* ... */
A = B;
However, I wouldn't recommend doing this in most places unless it makes logical sense that the array should be encapsulated.
-
Or, you could *gasp* use a vector.
http://www.parashift.com/c++-faq-lit....html#faq-34.1
Code:
#include <vector>
// ...
std::vector<int> intvec1;
// ...
std::vector<int> intvec2(intvec1);