开发者

Sequence of execution of a program

I have a question regarding the execution of the following program.

#include<stdio.h>

int main(void)  
{    
    char *p="hey friends",*p1;  
    p1=p;  
    while(*p!='\0')  
    {  
        p++;  
        printf("\n%p",p);  
    }  
    printf("%s %s",p,p1);  
    sleep(100);  
}  

When I ran the below it is giving the output as follows:

0x8048521  
0x8048522  
0x8048523  
0x8048524  
0x8048525  
0x8048526  
0x8048527  
0x8048528  
0x8048529  
0x804852a  

and then after 100 seconds it is printing "0x804852b hey friends". Although the statement: printf("%s %s",p,p1); is before the sleep statement then why it is not printing before goin开发者_JAVA技巧g to sleep and moreover it is printing one more address means it is entering the loop one more time.Can somebody please explain me the working of the above program. Whether is it related to the printf function's buffer?


stdout is line buffered. When you printf a \n or exit your application, the actual printout happens.

Use:

printf("%s %s\n",p,p1);

Or:

fflush(stdout);

EDIT: Address the other question...

printf("\n%p",p);

This prints a newline first and then an address.

printf("%s %s",p,p1); 

This prints an empty string (since p points to the 0 terminator) a space and the original string.

When the loop is done, you've printed the last address (but it's not flushed). You sleep, and then you print an empty string, a space, and the original string.

If you changed the last printf to use "%p %s" it'd be more clear what's happening.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜