Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'\0' and printf() in C

Tags:

In an introductory course of C, I have learned that while storing the strings are stored with null character \0 at the end of it. But what if I wanted to print a string, say printf("hello") although I've found that that it doesn't end with \0 by following statement

printf("%d", printf("hello"));  Output: 5 

but this seem to be inconsistent, as far I know that variable like strings get stored in main memory and I guess while printing something it might also be stored in main memory, then why the difference?

like image 987
u_sre Avatar asked Feb 07 '20 12:02

u_sre


People also ask

What is printf () in C?

"printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (lexing aka. parsing).

What does \0 represent in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string.

Can you print \0 in C?

If you want to print a \ you need to escape that (since \ is a special character itself). Put \\ in your string to print \ . If you want to print \\ your format string has to be \\\\ (i.e. escape both \ s).

What is printf \n in C?

The escape sequence \n means newline. When a newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next line on the screen.


2 Answers

The null byte marks the end of a string. It isn't counted in the length of the string and isn't printed when a string is printed with printf. Basically, the null byte tells functions that do string manipulation when to stop.

Where you will see a difference is if you create a char array initialized with a string. Using the sizeof operator will reflect the size of the array including the null byte. For example:

char str[] = "hello"; printf("len=%zu\n", strlen(str));     // prints 5 printf("size=%zu\n", sizeof(str));    // prints 6 
like image 116
dbush Avatar answered Oct 06 '22 07:10

dbush


printf returns the number of the characters printed. '\0' is not printed - it just signals that the are no more chars in this string. It is not counted towards the string length as well

int main() {     char string[] = "hello";      printf("szieof(string) = %zu, strlen(string) = %zu\n", sizeof(string), strlen(string)); } 

https://godbolt.org/z/wYn33e

sizeof(string) = 6, strlen(string) = 5 
like image 37
0___________ Avatar answered Oct 06 '22 07:10

0___________