Sunday 29 January 2012

Frequently Asked Questions in Technical Round at MNCs like TCS, WIPRO, INFOSYS,..etc – 6

Predict the output or error(s) for the following:


1)

main( )

{

 void *vp;


 char ch = ‘g’, *cp = “goofy”;


 int j = 20;


 vp = &ch;


 printf(“%c”, *(char *)vp);


 vp = &j;


 printf(“%d”,*(int *)vp);


 vp = cp;


 printf(“%s”,(char *)vp + 3);


}

Answer:

g20fy


Explanation:

Since a void pointer is used it can be type casted to any  other type pointer. vp = &ch  stores address of char ch and the next statement prints the value stored in vp after type casting it to the proper data type pointer. the output is ‘g’. Similarly  the output from second printf is ‘20’. The third printf statement type casts it to print the string from the 4th value hence the output is ‘fy’.


2)

main( )

{

 char  *q;


 int  j;


 for (j=0; j<3; j++) scanf(“%s” ,(q+j));


 for (j=0; j<3; j++) printf(“%c” ,*(q+j));


 for (j=0; j<3; j++) printf(“%s” ,(q+j));


}

Explanation:

Here we have only one pointer to type char and since we take input in the same pointer thus we keep writing over in the same location, each time shifting the pointer value by 1. Suppose the inputs are MOUSE,  TRACK and VIRTUAL. Then for the first input suppose the pointer starts at location 100 then the input one is stored as


When the second input is given the pointer is incremented as j value becomes 1, so the input is filled in memory starting from 101.


The third input  starts filling from the location 102



This is the final value stored .

The first printf prints the values at the position q, q+1 and q+2  = M T V

The second printf prints three strings starting from locations q, q+1, q+2

 i.e  MTVIRTUAL, TVIRTUAL and VIRTUAL.

No comments:

Post a Comment