struct S {
double arr[1];
S(double arr[1]) : arr(arr) {}
};
int main(void) {
double arr[1] = {1.2};
S p(arr);
return 0;
}
Hi, this is an extracted problem I encountered in my code.
Do you know why this code won't compile?
main.cpp: In constructor ‘S::S(double*)’:
main.cpp:26:28: error: incompatible types in assignment of ‘double*’ to ‘double [1]’
S(double arr[1]) : arr(arr) {}
I am using g++
, compiling and running with
g++ -std=c++17 main.cpp kdtree.h kdtree.cpp && ./a.out
Arrays can't be copied.
int a[3];
int b[3];
a = b; // illegal
Further, when you pass an array to a function, its name decays to a pointer, so S(double arr[1])
is equivalent to S(double* arr)
. Once you're inside the function, you have to copy the individual elements, so you also need the size of the array:
S(double *x, std::size_t sz) {
std::copy_n(x, sz, arr);
}
You can omit the size if you write the template as a function:
template <std::size_t sz)
S(double (&x)[sz]) {
std::copy_n(x, sz, arr);
}
Or, even better, use std::array
, which works the way you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With