Joachim
Joachim

Reputation: 499

C++: misunderstanding memory address and copy values of pointers

I thought I had understood the concept of pointers until going through this example (see "declaring pointers"), second example, which states the following:

#include <iostream>
using namespace std;

int main ()
{
  int firstvalue = 5, secondvalue = 15;
  int * p1, * p2;

  p1 = &firstvalue;  // p1 = address of firstvalue
  p2 = &secondvalue; // p2 = address of secondvalue
  *p1 = 10;          // value pointed to by p1 = 10
  *p2 = *p1;         // value pointed to by p2 = value pointed to by p1
  p1 = p2;           // p1 = p2 (value of pointer is copied)
  *p1 = 20;          // value pointed to by p1 = 20

  cout << "firstvalue is " << firstvalue << '\n';
  cout << "secondvalue is " << secondvalue << '\n';
  return 0;
}

having as result:

firstvalue is 10
secondvalue is 20

My question is: why is *p1=firstvalue not 20 ? Because they share the same memory adress. So as far as I know, one memory adress cannot have 2 different values. My reasonning is the following:

*p1 = 10 //firstvalue=10, *p2=secondvalue=15
*p2 = *p1 //*p1=firstvalue=secondvalue=*p2=10
p1 = p2 //*p1=*p2, now firstvalue and secondvalue share the same memory adress 
*p1 = 20 //*p2=*p1 (because they have the same memory adress) so firstvalue=secondvalue=20

Any help would be highly appreciated. Thanks in advance.

Upvotes: 0

Views: 179

Answers (1)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5222

The code:

p1 = &firstvalue; // p1 = address of firstvalue 
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10 
*p2 = *p1; // value pointed to by p2 = value pointed to by p1 
p1 = p2; // p1 = p2 (value of pointer is copied) 
*p1 = 20; // value pointed to by p1 = 20 

Can be rewritten as

p1 = &firstvalue; // p1 = address of firstvalue 
p2 = &secondvalue; // p2 = address of secondvalue
firstValue = 10; // value pointed to by p1 = 10 
secondValue = firstValue; // value pointed to by p2 = value pointed to by p1 
p1 = &secondvalue; // p1 = p2 (value of pointer is copied) 
secondValue = 20; // value pointed to by p1 = 20 

Upvotes: 2

Related Questions