The difference between p2 = p1 and *p2 = *p1

1997 views c++
4

Code from here: http://www.cplusplus.com/doc/tutorial/pointers/

#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;
}

My question is in the pointer statements. *p2 = *p1 means that p2 is now pointing to whatever value p1 is pointing to. Yet, p2 = p1 means that p1's value is now copied into p2. How can it be copied into it if pointer cannot hold values themselves? Wouldn't it just point to the same value?

answered question

Pointers are values themselves. Consider int a, *b, **c; c = &b; *c = &a; *b = 42;.

1 Answer

11

I guess you mean p1 = p2 (meaning that the value of p2 is copied to p1). Pointers hold addresses within the (virtual) memory.

Thus, p1 is now holding the value of p2, which is the address of secondvalue. In

*p1 = 20;

The value at memory address p1 (which is the same as p2) takes now the value 20.

firstvalue remains unchanged and is not referenced anymore by either of the two pointers p1 and p2

posted this

Have an answer?

JD

Please login first before posting an answer.