i'm writing arduino program in c++ , have following question:
why work
double* getarray() { double p, r, y; double ret[3] = {p, r, y}; return ret; }
but doesn't
double* getarray() { double p, r, y; return {p, r, y}; }
neither of code blocks work.
the first 1 compiles introduces undefined behavior return pointer array no longer exist. detailed answer on please see can local variable's memory accessed outside scope?
the second code block fails compile {p, r, y}
not valid initializer double*
.
what need here std::vector<double>
, std::array<double, some_constant_size>
or std::unique_ptr<double[]>
. if cannot use of need dynamically create array , need remember delete array when don like
double* getarray() { double * arr = new double[3]{1,2,3}; return arr; } int main() { double* foo = getarray(); // use array here delete [] foo; }
Comments
Post a Comment