Originally Posted by
stahta01
In C, you can NOT copy arrays; I think this also applies to C++.
Correct for C arrays (there are C++ arrays, too, namely std::array [C+11 addition]).
So first, the language forbids that you copy a C array into another one. That's a relic from C. You can copy a C++ array into another:
Code:
std::array<int, 10> a1, a2;
a1 = a2;
a2 = a1;
Secondly, you name "dynamic array."
But the thing is, you are just using dynamic memory and assigning the address at the start of the array to a pointer. How is the compiler supposed to know what the pointer is actually pointing to? It doesn't. That is why you cannot assign a pointer to an array, regardless of what that pointer is pointing to. Another relic from C.
You cannot assign a fixed array to a dynamic array, either. You think you can, but you can't. The reality is that the address of the first element in the array is copied into the pointer. So the array the pointer is pointing is lost to the void and you get a memory leak. Another relic from C.
You can copy a static array into a dynamic array and vice versa in C++. It is a little tricky, however, but here is how to do it:
Code:
std::vector<int> v; // Dynamic vector
// Fill v with some stuff
std::array<int, 10> arr;
std::copy(v.begin(), v.begin() + arr.size(), arr.begin()); // Important note: std::copy is stupid and will do a buffer overrun if you don't specify the bounds properly, so don't use v.end().
The reverse is also possible in different ways. The safest way is:
Code:
#include <iterator>
#include <vector>
#include <array>
#include <algorithm>
int main()
{
std::array<int, 10> arr;
std::vector<int> v;
std::copy(arr.begin(), arr.end(), std::back_inserter(v));
}