-
Returning a pointer
Hi,
I have a real beginner question for you all.
Code:
double * GetSalary()
{
double salary = 26.48;
double *HourlySalary = &salary;
return HourlySalary;
}
I found the example above on a website. I thought that a double declared in a function is allocated space on the run-time stack and is destroyed after the function returns. So if you then have
Code:
main()
{
double * ptr = GetSalary();
}
aren't you then going to have ptr pointing to an address in memory that will be holding different data?
Also, when GetSalary() returns, does the pointer HourlySalary get destroyed just like any other primitive upon return?
Thanks
-
Correct. Either the website gives bad examples, or it was meant as a counter-example.
To be precise, the pointer will point to a location that is simply invalid. It's undefined what data it holds. (Until you call another function, it will probably still hold the old value, which makes this even more dangerous: it often appears to work.)