pointers and references

+1 roger sheru · November 3, 2015
consider this code:

int  *pPointer;
void SomeFunction()
    int nNumber;
    nNumber = 25;    
    pPointer = &nNumber;
void  main()
    cout<< "Value of *pPointer: "<< *pPointer <<endl;

this code is problematic, because the variable nNumer is deallocated when the function ends, and
therefore the last line might cause run time exception or printing garbage  (correct me if I'm wrong).
now I need to fix this code, so it will print '25' for sure after the last line, and I thought of declaring nNumber at the same place where *pPointer is declared (instead of declaring it at the function scope).
the code works fine when I do that, however something here seems wrong too.
Do you think there is a better way?

Post a Reply


Oldest  Newest  Rating
0 Gauri Shankar Badola · November 3, 2015
See the thing is, as soon as that closing curly braces of SomeFunction() is encountered, the program flushes down all the local variables of that function Since *pPointer is a global variable, it will hold the address it points to, but the value at that address(the variable nNumber) will be flushed.
Solution 1 : make nNumber a global variable,which you did by declaring it with pPointer.
Solution 2 :   change the program a little bit and make the function return the variable.
  • 1



Used in many types of software including music players, video games, and many large scale applications.

Bucky Roberts Administrator