Passing array with fixed size in struct

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 issue that I encountered in my code.

Do you know why this code will not compile?

main.cpp: In constructorS::S(double*)’:
main.cpp:26:28: error: incompatible types in assignment ofdouble*’ todouble [1]S(double arr[1]) : arr(arr) {}

I use g++, compiling and working with

 g++ -std=c++17 main.cpp kdtree.h kdtree.cpp && ./a.out
+4
source share
4 answers

Arrays cannot 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, therefore it is S(double arr[1])equivalent S(double* arr). When you are inside the function, you need 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::arrayone that works as you expect.

+7
source

Do you know why this code will not compile?

, ( , ).

, . , : std::copy.

std::array, ++ 11. std::array .

+6

. std:: array:

struct S {
    std::array<double, 1> arr;
    S(std::array<double, 1> arr) : arr(arr) {}
};
+3

, , .

However, the arr member in the structure still has an array type. And a pointer cannot be assigned to an array (hence an error).

It is also impossible to assign one array to another (for example, even if you change it to one of the methods described in the link above), so you need to copy the elements manually using a loop or using std::copy, or use std::array, as in Ron's answer.

+3
source

Source: https://habr.com/ru/post/1691522/


All Articles