Pointers question

Im studying for my final and I was given this, the answer is , 15 15:


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
1
2
3
4
5
6
7
8
int *p1, *p2;             // p1 & p2 could point anywhere.
p1 = new int;             // p1 points to a newly allocated int, could be any value.
p2 = new int;             // p2 points to a newly allocated int, could be any value.
*p1 = 10;                 // *p1 is 10, *p2 could be any value.
*p2 = *p1 + 10;           // *p1 is 10, *p2 is 20.
p2 = p1;                  // *p1 is 10, p2 points to *p1, so *p2 is 10.   Memory leak here.
*p2 = *p1 + 5;            // *p1 is 10 at the start, but sincee p2 points to p1, both *p1 and *p2 are 15 after the assignment..
cout << *p1 << " " << *p2 << endl; //??? 
Well hope you can understand somthing from this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// defining 2 new pointers which points to nothing
int *p1, *p2; 
//new int : it allocate a new memory which can hold an object of type integer
// p1 is now pointing to that newly allocated memory
p1 = new int; 
// same here, though p2 now points to another newly allocated memory
p2 = new int; 
//here the * dereference the pointer and accessing the value stored in the pointed memory
// so here p1 points to a memory that stores a value of (int) 10
*p1 = 10;
// same here the * dereferences the pointer 
// p2 now is pointing to a memory that store a value of (int) 10+10 = 20
*p2 = *p1 + 10; 
// at this line p2 will point to the same memory that p1 points to
// so by dereferencing p1 or p2 they will give the same value
//as they both point to the same memory and any change to the value stored in that memory
//with either of them is the same
// so p2 now points to a memory of stored value (int) 10
p2 = p1;
//at thise line p2 stored memory value is changed to be of value (int) 10 + 5 = 15
// both p2 and p1  point to the same memory that have a stored value of (int) 15 
*p2 = *p1 + 5; //15?
// here it dereference both pointers to get the value stored in the memory
cout << *p1 << " " << *p2 << endl; //??? 
Last edited on
Wow thank you guys sooo much. Especially for being as descriptive as possible
Topic archived. No new replies allowed.