0

Rookie to C++ and can not understand the function passed by pointer and reference. Here is an example to describe the problem I meet.

#include <iostream>
#include <math.h>

using namespace std;

void getsincos( double x, double *&sinx, double *&cosx );

int main()
{
    double x = 30;
    double *sinx;
    double *cosx;

    getsincos( x, sinx, cosx );

    //cout << *sinx << endl;
    cout << *cosx << endl;

    return 0;
}

void getsincos( double x, double *&sinx, double *&cosx ){
    double temps, tempc;
    temps = sin( x );
    tempc = cos( x );
    sinx = &temps;
    cosx = &tempc;
    cout << *sinx << endl;
    cout << *cosx << endl;
}

I commented out the line cout << *sinx << endl;, the output is:

-0.988032
0.154251
0.154251

the first two come from the function definition and the last one comes from the main function. So next step, if I recovery the line cout << *sinx << endl;, the results are:

-0.988032
0.154251
-0.988032
6.95324e-310

definitely, the last one is wrong, it is an random number. Sorry that I do not find the error, could anyone give some explanation on it. Thanks.

Fly_back
  • 259
  • 1
  • 5
  • 16
  • You are taking the address of automatic variables. Automatic variables are destroyed when out of the scope. – Daniele May 15 '15 at 09:04
  • Thanks @Daniele, so it means that I can only refer the function one time, otherwise, I need to run the function again? – Fly_back May 15 '15 at 09:59
  • I think you should study how things work in C++. There is a lot of leterature... and this is a very common problem. – Daniele May 15 '15 at 12:32

0 Answers0