
Michael L. answered 09/30/20
Multiple Years Teaching Others & 4.0 Grades in Computer Science
Hello!
As detailed above in the video, the issue with this code is that x, inside of get_val(), will only exist for as long as the function is running. When you return the reference to x (&x), you're returning memory that has been deleted after the function exits.
The fix to this is making x's memory dynamic. We do this by first saying that x is no longer an int, but an int pointer
Then, we give x a default value of 200
Next, we add the value of y to x
Finally, we fix the return statement by simply returning x, as x's value (without dereferencing) is the, in fact, the memory that holds the answer to our calculation (200 + 10 = 210).
Please feel free to reach out with any more questions :)
Michael