Simulate the fragment of codes below and trace the output.
int *p1, *p2;
p1 = new int;
p2 = new int;
*p1 = 10;
*p2 = 20;
cout << *p1 << “ ” << *p2 << endl;
p1 = p2;
cout << *p1 << “ ” << *p2 << endl;
*p2 = 30;
cout << *p1 << “ ” << *p2 << endl;
#include <iostream>
using namespace std;
int main() {
// 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; //???
return 0;
}
Comments
Leave a comment