What is the output produced by the following code? int *p1, *p2; p1 new int; p2 new int p1 10

Question:

Answer:

int *p1, *p2;   //declare 2 integer pointer
p1 = new int;   //allocating a storage for an integer and assigning address of that storage to p1
p2 = new int;   //allocating a storage for an integer and assigning address of that storage to p2
*p1 = 10;       //storing 10 to the address p1
*p2 = 20;       //storing 20 to the address p2
cout << *p1 << " " << *p2 << endl;  //print the data at storage p1 and p2 i.e 10 and 20
p1 = p2;    //making pointer p1 and p2 point to same location i.e location of p2
cout << *p1 << " " << *p2 << endl;  //print 20 20 as both are pointing to same location
*p1 = 30;   //storing 30 to address p1
cout << *p1 << " " << *p2 << endl;  //printing 30 30

hence output produced

10 20
20 20
30 30

if we change the code with *p2 = 30 instead of *p1 = 30 then there will be no change in output code as consider a situation

let xyz is an address

let store xyz address in two variable p1 and p2

i.e

p1 = xyz as well as

p2 = xyz

now if somebody says that put k at place p1 is also the same as saying put k at place p2 as both p1 and p2 pointing to the same place

Leave a Comment

Your email address will not be published. Required fields are marked *