Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array with fixed size to struct

Tags:

c++

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
like image 499
Dan Zilberman Avatar asked Dec 01 '22 14:12

Dan Zilberman


1 Answers

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.

like image 142
Pete Becker Avatar answered Dec 19 '22 02:12

Pete Becker