COMPUTER SCIENCE POINTER

2001:

1.c) Identify the syntax error(s), if any, in the following program. Also give reason for errors.

void main( )
{const int i=20;
const int* const ptr=&i;
(*ptr)++;
int j=15;
ptr=&j;
}

2

Ans:
Error Line 5 : Cannot modify a const object.
Error Line 7 : Cannot modify a const object.Warning Line 8 : ‘j’ is assigned a value that is never used.Warning Line 8 : ‘ptr’ is assigned a value that is never used.

Explonation:
(1) Error 1 is in Line no.5 ie (*ptr)++. Here ptr is a constant pointer ie the contents cann’t be modified.
(2) Error 2 is in Line no.7 ie ptr=&j;.Here ptr is a constant pointer the address in this pointer can’t be modified. (It is already pointing the address of i.)

1.d) Give the output of the following program segment. (Assuming all required header files are included in the program).

void main( )
{ int a=32,*x=&a;
char ch=65,&cho=ch;
cho+=a;
*x+=ch;
cout<<a<<’,’<<ch<<endl; }

2

2.a) Distinguish between

int *ptr=new int(5);
int *ptr=new int[5]; 2

Ans: The int *ptr=new int(5); declares and creates the space for the new data directly.Ie The new operator reserves 2 bytes of memory from heap memory (free pool) and returns the address of that memory location to a pointer variable called ptr, 5 is the initial value to be stored in the newly allocated memory.

The int *ptr = new int[5]; initializes an array element. A memory space for an integer type of array having 5 elements will be created from the heap memory (free pool).

 

CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )