Jacksonkr Jacksonkr - 3 months ago 31
C++ Question

cannot convert '<brace-enclosed initializer list>' to 'double' in return

I'm writing an Arduino program in c++ and have the following question:

Why does this work

double* getArray() {
double p, r, y;

double ret[3] = {p, r, y};
return ret;
}


but this doesn't

double* getArray() {
double p, r, y;

return {p, r, y};
}

Answer

Neither of your code blocks work.

The first one compiles but introduces undefined behavior as you return a pointer to a array that no longer exist.

The second code block fails to compile as {p, r, y} is not a valid initializer for a double*.

What you really need here is a std::vector<double>, std::array<double, some_constant_size> or std::unique_ptr<double[]>. If you cannot use any of those then you need to dynamically create the array and then you need to remember to delete that array when you are don with it like

double* getArray() {
    double * arr = new double[3]{1,2,3};
    return arr;
}

int main() {
    double* foo = getArray();
    // use array here
    delete [] foo;
}
Comments