0

I have a function to calculate square of a number. I expect output 9 when called sqr(3). But answer is wrong. The compiler gives warning about address of local variable returned but I cannot decipher that warning. Another question in the declaration double* v1 = sqr(v2), why not double* v1 = &sqr(v2) as one would do in case of other cases like int a=5; int *b=&a?

#include <iostream>

double* sqr(double d)
{
    double s = d*d;
    return &s;
}


int main()
{
  double v2 = 3.;
  double* v1 = sqr(v2); //question why not double* v1 = &sqr(v2)
  std::cout<<*v1;
}
  • Please explain the reasoning for using a pointer as return value. Then change your code to not return the address of a local variable. – Yunnosch Mar 04 '19 at 00:07
  • Please describe in English what you understanding of what the function does is. Then describe what you want it to do. – Yunnosch Mar 04 '19 at 00:09
  • I do not understand the question in the comment. – Yunnosch Mar 04 '19 at 00:09
  • Just trying to understand things so using pointer. Otherwise, just using plain `double` return type will work too. – dfd4334 Mar 04 '19 at 00:09
  • Is the function returning a wrong pointer? Yes. All addresses to local variables are wrong as soon as the function is left. – Yunnosch Mar 04 '19 at 00:10
  • For understanding pointers, experimenting with random code will not teach you. Find a tutorial and/or a book. – Yunnosch Mar 04 '19 at 00:11

1 Answers1

0

In the below function, s is a double allocated on the function callstack. You're returning the address of that variable.

When you return from the function, that stack unwinds, resulting in the return value pointing to invalid memory (aka address of local variable)

double* sqr(double d)
{
    double s = d*d;
    return &s;
}

tinkertime
  • 2,972
  • 4
  • 30
  • 45