what will the output?

indian.21987's Avatar
Light Poster
Code:
main() 
{ 
        char *p1=“name”; 
        char *p2; 
        p2=(char*)malloc(20); 
        memset (p2, 0, 20); 
        while(*p2++ = *p1++); 
        printf(“%s\n”,p2); 

}
Also what is the use of malloc() function?
EDIT: Please read the "Before you make a query" thread (see the upper right corner of this page).

Last edited by DaWei; 21Aug2007 at 13:50.. Reason: Add code tags
seeguna's Avatar
Go4Expert Member
What u exactly want in this program?


Malloc() is used for dynamic memory allocation.........
Memset() is used to Set buffers for the character........
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Malloc will allocate 20 char of memory from the heap. Memset will set it to zeroes. "Name" will be copied there. Please note that you cannot use the type of quotes that you show. Use "".
indian.21987's Avatar
Light Poster
thanks a lot. Got the idea about malloc,memset fns.
my question is,,

what will be the output for the above program????
DaWei's Avatar, Join Date: Dec 2006
Team Leader
The output will be Name, presuming you correct your quote characters. The line,
Code:
while(*p2++ = *p1++);
will check to see if the assignment of *p1 to *p2 is non-zero. On the first operation if will be non-zero (it will be 'N'). It will then increment p1 and p2 to the next location and do it again. This will continue until it assigns the terminating 0, then it will exit. Thus, the contents pointed to by p1 are copied to the area pointed to by p2.

This is the sort of thing you should compile and test. You would have learned two things: not to use balanced quote characters, and what the program would output.
listendinesh's Avatar, Join Date: Aug 2007
Go4Expert Member
I have some doubts about output.malloc will allocate a chunk of 20 bytes to p2 and we set that buffer with 0. In the while loop we are incrementing both p1 and p2 for copying string. After while loop complete "name" whould be copied into buffer returned by malloc but p2 will point sixth byte of buffer which contain 0.So when printf statement will execute to print string pointed by p2 it would print nothing.
seeguna's Avatar
Go4Expert Member
What Dinesh said is right.........
This program doesn't print anything....
DaWei's Avatar, Join Date: Dec 2006
Team Leader
Actually, you are correct, my oversight. p2 will point to the byte AFTER the terminating 0, which is also a zero because of the memset. Thus, it will be a null string. Without the memset, it might print a bunch of junk.
indian.21987's Avatar
Light Poster
Ahhh! Clearly unterstood.
thank U all.........