ALLInterview.com :: Home Page            
 Advertise your Business Here     
Browse  |   Placement Papers  |   Company  |   Code Snippets  |   Certifications  |   Visa Questions
Post Question  |   Post Answer  |   My Panel  |   Search  |   Articles  |   Topics  |   ERRORS new
   Refer this Site  Refer This Site to Your Friends  Site Map  Bookmark this Site  Set it as your HomePage  Contact Us     Login  |  Sign Up                      
tip   SiteMap shows list of All Categories in this site.
Google
   
 
Categories  >>  Software  >>  Programming Languages  >>  C
 
 
 
Question
main()
{
	char *p1="Name";
	char *p2;
	p2=(char *)malloc(20);
	while(*p2++=*p1++);
	printf("%s\n",p2);
}
what is the output?



 Question Asked At :: Ramco
 Question Submitted By :: naveed
I also faced this Question!!     Rank Answer Posted By  
 
Answer
Hi all,

#1 Mannucse's ans is wrong. cos as mentioned "Name" will 
not be the output.

#2 Sanath's ans is wrong. Cos at the end of the while loop, 
p2 will not point to NULL. It will point to the next byte 
to the NULL termination ie., 6th byte.    

#3 Shruti's ans is wrong. cos i think she got confused 
between assignment(=) and comparisonal(==) operators. And 
the statement given as "we cannot copy the value of p1 in 
p2, the way its mentioned here" is absolutely wrong.


So,
Lets Analyse the program and how to get the required output.

hav a look on th program again.

main() 
{ 
char *p1="Name"; 
char *p2; 
p2=(char *)malloc(20); 
while(*p2++ = *p1++)
{
	printf("TEST \n");
}
printf("%s\n",p2); 
getch();
}  

Here, in every iteration of while loop, we are assigning 
*p1 to *p2, and incrementing both pointers p1 and p2, After 
completion(when *p1 value would be '\0')of the while loop, 
first 5 bytes of p2 holds the 
characters 'N','a','m','e' '\0'. At the end of while loop 
p2 points to the 6th byte in the memory.

So, now printf("%s\n",p2); shall start print the values 
from the 6th byte to 20th bytes of the memory which was 
allocated dynamically.
----------------------------------
To get the desired output change the printf statement to 
printf("%s\n",p2-5); 

Now (p2-5) points to the starting address of p2 and will 
print the values in the memory till it encounters '\0' 
termination. ie., The output would be -> Name

 
Vadivel T
 
View All Answers
 
 
 
 
 


   
Copyright Policy  |  Terms of Service  |  Help  |  Site Map 1  |  Articles  |  Site Map  |   Site Map  |  Contact Us interview questions urls   External Links 
   
Copyright © 2012  ALLInterview.com.  All Rights Reserved.

ALLInterview.com   ::  Forum9.com   ::  KalAajKal.com