Misunderstanding something about pointers?

It seems like i do not fully understand how pointers works. I would be very
thankfull if someone would explain to me what i am missing.

Highlighting the pointer with red to make it clearer what i talk about.

{

---> Okay NodeReceiver here is the pointer that i am interested in.
---> When i send it to the function checkForNodeEdgeAt, i was expecting
---> the value it received in there to remain when it got out of the function.


CNode *NodeReceiver = NULL;
int iEdgeNrReceived = 0;


---> Call to function that changes NodeReceiver

CNodeMgr::getSingleton().checkForNodeEdgeAt( miMouseX , miMouseY , NodeReceiver , iEdgeNrReceived);


}

---> The function that is beeing called

void CNodeMgr::checkForNodeEdgeAt(int iXPos, int iYPos, CNode* NodeReceiver, int &iEdgeNrReceiver)

{
   map<
unsigned int,CNode*> ::iterator next = mNodes.begin();          
   while(next != mNodes.end())
   {

      iEdgeNrReceiver = next->second->checkForNodeEdgeAt(iXPos, iYPos);  
      
      
if(iEdgeNrReceiver != -1)  
      {

         NodeReceiver = next->second

---> Using the debugger and stepping trough the code
---> i can see that the NodeReceiver now looks like this:
---> "+  NodeReceiver 0x003d5d30 {miNodeID=3 miX=300 miY=400 ...} CNode *"


         break;
      }

      next++;

   }

}


Once it gets back to the calling function, it reverts to:
+  NodeReceiver 0x00000000 {miNodeID= miX= miY= ...} CNode *

How come



Answer this question

Misunderstanding something about pointers?

  • Dejjan

    Because the CNode* is passed by value, meaning it's a copy of the original pointer.  Whatever happens to the copy has no effect on the original.  It's the same as something like this.

    {
        int i = 20;
        some_func( i );
    // at this point 'i' is still 20 because the value was passed to the function, not the actual variable.
    }

    void some_func( int i ){
        i = 10;
    }

  • DentonChris

    Ah, I did not think of that. So used to the fact that values can be changed so i just never thought about that the pointer itself could not be changed. thank you very much for a quick answer and for teaching me something new!


  • Lesley-Ann Vaughan

    This is exactly the same as doing the following:

    void f(int i)
    {
       i += 2;
    }

    int main()
    {
       int i = 0;

       f(i);
    }

    The variable 'i' is passed by value and hence any change you make to it within the function f will not be reflected in the calling function.

    In C++ pointers are also passed by value: so while you can change the object that the pointer points to you cannot change the pointer itself. If you want to change the pointer then you need to pass it by reference. For example:

    void f(X*& pX)
    {
       pX = new X();
    }

    int main()
    {
       X* pX = NULL;

       f(pX);
    }


  • Pairair

    So how would i go about to avoid this
  • Misunderstanding something about pointers?