As I was trying to understand more the behavior of some functions I took two examples :
char str[]="Hello\0World"
and
char str[100];
scanf("%s",str);// enter the same string "Hello\0world"
The problem here that in the first example I got Hello
and in the second I got Hello\0world
why are the two characters \
and 0
interepreted as an end character of string in the first and not in the second one ?
\0
is an escape sequence, and while it consists of two characters in the source file, it is interpreted as a single character in the string, namely the null character. However, this special interpretation only happens in the source file; if you input \0
when you run the program, it gets interpreted literally as the two characters \
and 0
.
Because when you enter "Hello\0World" for the scanf
then you don't enter the same.
When you use \0
in the code that means a character with ascii code 0. Whereas when you're prompted these escape sequences are not interpreted. You actually entering a backslash and a zero character.
So your input will be equal to "Hello\0World" not Hello\0 World
\0
is one character. In first case it is written in code so treated as special sign, like new line (\n
) or similar, so printing function stops here. In second case you are literally inputting two separate characters in one byte you have \
and in second 0
so it is not threaten as termination sign. If you want to place "real" \0
from keyboard look here How to simulate NUL character from keyboard?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With