pointers

Discussion in 'Computer Science & Culture' started by Gunjan, Jul 18, 2003.

Thread Status:
Not open for further replies.
  1. Gunjan Registered Member

    Messages:
    12
    I can not understand the following program:
    Code:
    #include <iostream.h>
    
    int main ()
    {
      int value1 = 5, value2 = 15;
      int *p1, *p2;
    
      p1 = &value1;     // p1 = address of value1
      p2 = &value2;     // p2 = address of value2
      *p1 = 10;         // value pointed by p1 = 10
      *p2 = *p1;        // value pointed by p2 = value pointed by p1
      p1 = p2;           // p1 = p2 (value of pointer copied)
      *p1 = 20;         // value pointed by p1 = 20
      
      cout << "value1==" << value1 << "/ value2==" << value2;
      return 0;
    }
    
    why the out put 10(value1) and 20(value2) here?
    I do not understand the statement p1=p2 specially.
    Thank you.
     
  2. Google AdSense Guest Advertisement



    to hide all adverts.
  3. okinrus Registered Senior Member

    Messages:
    2,669
    v1 v2
    10 10
    10 20

    p1 = p2 assigns p1 the value of pointer p2. So because p2 == &value2, after the assignment, p1 == &value2. This is why *p2 changes value2 and not value1.
     
  4. Google AdSense Guest Advertisement



    to hide all adverts.
  5. S.Tarafdar Registered Senior Member

    Messages:
    35
    What about the last line *p1=20?
    Doesn't it mean value1=20?
     
  6. Google AdSense Guest Advertisement



    to hide all adverts.
  7. okinrus Registered Senior Member

    Messages:
    2,669
    No. Your local variables are stored off the stack. For example,
    value1 might be stored in location 0x8000 and value2 in location 0x8004.

    When you assign p2 = &value2, you have p2 == 0x8004. Then when you assign p1 = p2, you get p1 = 0x8004. By dereferancing p1 you change value2.
     
  8. S.Tarafdar Registered Senior Member

    Messages:
    35
    Internet Tutorials

    Okinrus,I am struggling to understand what dereference operator is.Isn't it *?

    Then you see the online tutorial:

    http://www.cplusplus.com/doc/tutorial/tut3-3.html

    They mean it the other way round!!!!!!

    It really fooled me really...
     
  9. okinrus Registered Senior Member

    Messages:
    2,669
    Yeah that tutorials a bit <a href="http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Companion/cxx_crib/dereference.html">inaccurate</a> They confused referance operator with dereferance operator.
     
  10. S.Tarafdar Registered Senior Member

    Messages:
    35
    Thank you,okinrus.
     
Thread Status:
Not open for further replies.

Share This Page