Find the output for the following C programmain(){char *p1="Name";char *p2;p2=(char *)malloc(20);while(*p2++=*p1++);printf("%sn",p2);}

An empty string

  
Showing Answers 1 - 2 of 2 Answers

Girish

  • Jul 23rd, 2005
 

Can any on tell me the resone for empty out put . I thught the the out put will be some garbage value . 
 
because malloc() desnot intialise any value. I had tryed this program and i got the answer empty string . then i cahnged the program like this... 
int main() 

abc(); 
ab(); 
return 0; 

int abc() 

char *p1="Name"; 
char *p2="abcdefghidfsjlkdf"; 
free p2; 
return 0; 

int ab() 

char *p1="Name"; 
char *p2; 
p2=(char *)malloc(20); 
while(*p2++=*p1++); 
printf("%sn",p2); 

/* ther may be some sytax mistakes here , because i am writing here only */ 
 
in this i got some gurbage value . can any one explaine me a bit more on this...

  Was this answer useful?  Yes

harshita

  • Aug 6th, 2005
 

Answer : An empty string 
The main aim of this prg is to copy string p1 into p2 . In the while loop we keep on incrementing p2 and p1 . By the end of while loop the pointer p2 is shifted by 5 . So it prints out an empty string.  
Try the following: 
#include 
int p; 
int main() 

 
char *p1="Name"; 
char *p2, *p3; 
p2=(char *)malloc(20); 
p3=p2; 
while(*p2++=*p1++); 
printf("n%s",(p2-5)); 

 
It will print p2=Name

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions