You can copy a std::array
:
const std::array temp_WEIGHT {1, 2, 3, 4, 5, 6, 7, 8};
const auto new_WEIGHT = temp_WEIGHT;
You can convert (and copy) a C array to a C++ array with to_array:
const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
const auto new_WEIGHT = std::to_array(temp_WEIGHT);
You can access the underlying array with std::array<T,N>::data and the size with std::array<T,N>::size
#include <array>
#include <iostream>
void f(int arr[], std::size_t size) {
for (std::size_t i = 0; i < size; ++i) {
arr[i] *= 2;
}
}
int main() {
const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
auto new_WEIGHT = std::to_array(temp_WEIGHT);
f(new_WEIGHT.data(), new_WEIGHT.size());
for (const auto &el : new_WEIGHT) {
std::cout << el << ' ';
}
}
If you need a reference to a C array you can
#include <array>
#include <iostream>
template<std::size_t SIZE>
void f(int (&arr)[SIZE]) {
for (auto &el : arr) {
el *= 2;
}
}
int main() {
const int temp_WEIGHT[] = {1, 2, 3, 4, 5, 6, 7, 8};
auto new_WEIGHT = std::to_array(temp_WEIGHT);
f(*static_cast<int(*)[new_WEIGHT.size()]>(static_cast<void*>(new_WEIGHT.data())));
for (const auto &el : new_WEIGHT) {
std::cout << el << ' ';
}
}
From Is it legal to cast a pointer to array reference using static_cast in C++? I understand that this is well-defined and legal.
That said I don't see any reason to use C arrays today.