Hello, everybody.
first, look at the following code:
#include <iostream>
1 using std::cout;
2 using std::endl;
3 using std::cin;
4
5 double* treble(double);
6
7 int main(void)
8 {
9 double num = 5.0;
10 double* ptr = 0;
11 ptr = treble(num);
12 cout << endl
13 << "Three times num = " << 3.0*num << endl;
14 cout << "Result = " << *ptr;
15 cout << endl;
16 return 0;
17 }
18
19 double* treble(double data)
20 {
21 double result = 0.0;
22 result = 3.0*data;
23 return &result;
24 }
the output from this program is something like:
Three times num = 15
Result = 4.10416e-230
I know that the returned pointer of the function treble is point to local variable so when I returned, the value which inside that address has been lost.
there is no problem till here,
but let us to change the lines 13,14 to become:
13 << "Three times num = " << 3.0*num << endl
14 << "Result = " << *ptr;
the output will become:
Three times num = 15
Result = 15
why?