Why can I not copy a C-style array to std::array? [duplicate] Why can I not copy a C-style array to std::array? [duplicate] arrays arrays

Why can I not copy a C-style array to std::array? [duplicate]


In parameter declaration, int input[16] is same as int* input. And when you pass argument array would decay to pointer, both mean the information about size of the array is lost. And std::begin and std::end can't work with pointers.

You could change it to pass-by-reference, which reserve the array's size.

std::array<int,16> copyarray(int (&input)[16])

Note that you can only pass array with exact size of 16 to the function now.


Everything important said already, you can get the function just a little bit more flexible:

template <typename T, size_t N>std::array<T, N> copyarray(T const (&input)[N]){    std::array<T, N> result;    std::copy(std::begin(input), std::end(input), std::begin(result));    return result;}

(Late) edit: There is a disadvantage with the approach above: You'll need to copy the returned array on assignment, as it doesn't contain any truely movable data (that's the same for raw arrays already). You can avoid this drawback by directly copying into the target array:

template <typename T, size_t N>void copyarray(std::array<T, N>& target, T const (&source)[N]){    std::copy(std::begin(source), std::end(source), std::begin(target));}

This mimicks the assignment target = source; if you like better, you can swap the parameters, of course, to have the output parameter last.

Usage (as is):

int source[7] = { };std::array<int, sizeof(source)/sizeof(*source)> target;copyarray(target, source);


As stated already the problem here is that arrays decay to pointers when passed to a function, meaning that the size is not preserved.

If however you knew that there were 16 elements in the array you could do this:

array<int,16> copyarray(const int input[]) {    array<int, 16> result;    copy_n(input, size(result), begin(result));    return result;}