0

I have the following C++ function, trying to return an array of float:

float* get_my_weights(int e, int n, float a, float b) {
    float weights[10] = {1};
    weights[0] = e + n + a + b;
    return weights;
};

During the compilation, I got the following errors:

myFunction:4:12: error: address of stack memory associated with local variable 'weights' returned[-Werror,-Wreturn-stack-address]
    return weights;
           ^~~~~~~
1 error generated.

What did I do wrong here?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Edamame
  • 23,718
  • 73
  • 186
  • 320
  • 5
    `weights` doesn't exist after you return from `get_my_weights`. Your pointer to is is no longer usable. – François Andrieux Oct 25 '18 at 19:43
  • @FrançoisAndrieux Thanks! How do I fix this then? – Edamame Oct 25 '18 at 19:46
  • 4
    If you want to return an array by value, use `std::array` instead of a `float[10]`. Those can be copied around. Though a `std::vector` of size 10 may be more desirable since it offers move semantics. – François Andrieux Oct 25 '18 at 19:47
  • Beware that the answers in the duplicate are not very good... – François Andrieux Oct 25 '18 at 19:53
  • Side note: `float weights[10] = {1};` only sets the first element to 1. The remainder are all set to zero. This doesn't affect this program in any way, but it comes as a nasty surprise to many who expect it to produce an array of 1s. – user4581301 Oct 25 '18 at 21:03

0 Answers0