0

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};
}
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284

1 Answers1

6

Neither of your code blocks work.

The first one compiles but introduces undefined behavior as you return a pointer to an array that no longer exist. For a very detailed answer on this please see Can a local variable's memory be accessed outside its scope?

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;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402