Whats wrong with the following code Fix it int ptr new int

What\'s wrong with the following code? Fix it. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2;

Solution

if program is written in cpp... then everthing is fine with code.. it is correctly written

first a new address block of size int is created and assigned the block address to variable ptr

then , the value for the address block , 8 is assigned and stored to variable ptr

then,, an another new address block of size int is created and assigned the block address to variable ptr2

then , the value for the address block , -5 is assigned and stored to variable ptr2

finally ptr points to the value of ptr2

but.. if the program is written in c , then it has error..

// c doesn\'t new keyword..

//so we have to initialize ptr variables,with another variables statically or dynamically

//modified code

int a,b;

int *ptr=a;
   *ptr = 8;
   int *ptr2 = b;
   *ptr2= -5;
   ptr=ptr2;

 What\'s wrong with the following code? Fix it. int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2;Solutionif program is written in cpp..

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site