Misunderstanding with pointer program

I am looking over this program and the output is, 15 15 , but i dont know why? Could someone please explain this to me? :



#include <iostream>
#include <cmath>

using namespace std;

int main();
{

int *p1, *p2;
p1 = new int;
p2 = new int;
*p1 = 10;
*p2 = *p1 + 10;
p2 = p1;
*p2 = *p1 + 5;
cout << *p1 << " " << *p2 << endl;

return 0;

}
Last edited on
Try going step by step and noting what the states of variables are at each point. The key point you'll need to use your knowledge of pointers at is when you assign p2 to p1, as this changes the location that p2 is pointing to, nothing else.

You may also want to note that this program is leaking memory, but I imagine this is just an exercise.
Well im studying for my final and the only part given was this:


int *p1, *p2; // what is it pointing to
p1 = new int; //what does new int do
p2 = new int; //what does new int do
*p1 = 10;
*p2 = *p1 + 10; //20?
p2 = p1;
*p2 = *p1 + 5; //15?
cout << *p1 << " " << *p2 << endl; //???


I just dont understand it
Last edited on
Topic archived. No new replies allowed.