Anti Mafia
Anti Mafia

Reputation: 331

When my string contain null character in c program?

I still don't know, when my string in c program contain null-terminated and when it doesn't contain.

Sample of my code

...
float t0 = 2.43, t1 = 3.42, t2 = 1, t3 = 10.9;
...
printf("%.2f %.2f %.2f %.2f", t0, t1, t2, t3); 
...

If i use printf like in my code, does c program will automatically add null-terminated at the end of string that printed or no?

Upvotes: 0

Views: 588

Answers (4)

chux
chux

Reputation: 153303

Q: If i use printf like in my code, does c program will automatically add null-terminated at the end of string that printed or no?
A: No. printf() does not typical print the terminating null character '\0'. Instead "%.2f %.2f %.2f %.2f" causes output like "1.12 2.23 3.34 4.45" with the last character printed as '5'.

[Edit]
The format "%.2f %.2f %.2f %.2f" is a string which ends with a null terminator '\0'. The printed output of printf() did not print a '\0'. The null terminator '\0' in the format signals to printf() to stop. The null terminator '\0' itself is not printed.

Note: In C, a C string always has a terminating null character '\0'. If an array of char does not contain one, it is not a string. So the output of printf() in the above example is not a string, but simply a series of characters.

Upvotes: 2

alk
alk

Reputation: 70883

The 1st argument to

printf("%.2f %.2f %.2f %.2f", ...

is a string literal ("%.2f %.2f %.2f %.2f") and yes, also string literals are 0-terminated.

Upvotes: 1

antonpuz
antonpuz

Reputation: 3316

The answer to If i use printf like in my code, does the string that printed contain null character at the end? is yes it contains but you will not see it in printf.

The null terminator indicates the end of a string when represented as an array of characters. When using the printf function you pass a pointer to the beginning of the string as a parameter and it will print the string until the NULL terminator.

Upvotes: 0

phil
phil

Reputation: 565

Effectively yes, had you declared char format[]="%f %f\n"; Using gdb or adding some research code you'd be able to see the nul byte terminating the string.

Upvotes: 0

Related Questions