Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

c - Why does "printf" not produce any output?

I am learning to program in C. Could you explain why nothing is printed here?

#include <stdio.h>

int main (void)
{
    char a[]="abcde";
    printf ("%s", a);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On many systems printf is buffered, i.e. when you call printf the output is placed in a buffer instead of being printed immediately. The buffer will be flushed (aka the output printed) when you print a newline .

On all systems, your program will print despite the missing as the buffer is flushed when your program ends.

Typically you would still add the like:

printf ("%s
", a);

An alternative way to get the output immediately is to call fflush to flush the buffer. From the man page:

For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function.

Source: http://man7.org/linux/man-pages/man3/fflush.3.html

EDIT

As pointed out by @Barmar and quoted by @Alter Mann it is required that the buffer is flushed when the program ends.

Quote from @Alter Mann:

If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination.

See calling main() in main() in c


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...