Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   what will the output? (http://www.go4expert.com/forums/output-t5959/)

indian.21987 21Aug2007 13:01

what will the output?

        char *p1=“name”;
        char *p2;
        memset (p2, 0, 20);
        while(*p2++ = *p1++);


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).

seeguna 21Aug2007 13:43

Re: what will the output?
What u exactly want in this program?

Malloc() is used for dynamic memory allocation.........
Memset() is used to Set buffers for the character........

DaWei 21Aug2007 13:52

Re: what will the output?
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 23Aug2007 18:17

Re: what will the output?
thanks a lot. Got the idea about malloc,memset fns.
my question is,,

what will be the output for the above program????

DaWei 23Aug2007 20:09

Re: what will the output?
The output will be Name, presuming you correct your quote characters. The line,

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 24Aug2007 11:05

Re: what will the output?
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 24Aug2007 11:48

Re: what will the output?
What Dinesh said is right.........
This program doesn't print anything....

DaWei 24Aug2007 12:11

Re: what will the output?
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 25Aug2007 16:49

Re: what will the output?
Ahhh! Clearly unterstood.
thank U all.........

All times are GMT +5.5. The time now is 17:04.