Return pointer

I do not understand how this example can work:

double * GetSalary()  {
  double salary = 26.48; 
  return &salary;
}

main() {
    cout << *GetSalary();  //prints 26.48

}

salaryis a local variable in GetSalary(), therefore, after returning from this function, this cell can be overwritten by another function. I do not see how it is ever possible to work with a pointer to a local variable (not instanciated to a bunch).

+5
source share
6 answers

This does not work. This behavior is undefined. Perhaps this works because “right behavior” is a subset of “any possible behavior”.

+16
source

You are running undefined behavior, which means anything could happen . Including work.

(.. , , ).

, , , . , . , , , 26.48 . .

+8
double * GetSalary()  
{   
     double salary = 26.48;    
     return &salary; 
}  
double dummy_function()
{
     double a = 1.1;
     double b = 2.2;
     double c = 0 , d = 0;

     c = a + b - d;
     return c;  
}

main() 
{     
     double *a;
     a = GetSalary();
     cout << dummy_function();
     cout << *a;  //this time it wont print 26.48
} 

dummy_function

+2

"", , . , , , "" .

, , , .

+1

This is a dangling pointer that causes undefined behavior .
on some systems, this may cause your application to crash, while for others it may work correctly. But in any case, you should not do this.
see this similar SO entry .

0
source

It also works, but much safer. This will not work in a multi-threaded program.

double * GetSalary()  {
  static double salary = 26.48; 
  return &salary;
}
0
source

All Articles