Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The end character `\0` is it considered as one character or two characters?

Tags:

c++

c

gcc

scanf

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 ?

like image 296
tissa Avatar asked Dec 24 '14 14:12

tissa


3 Answers

\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.

like image 129
Aasmund Eldhuset Avatar answered Oct 11 '22 02:10

Aasmund Eldhuset


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

like image 1
fejese Avatar answered Oct 11 '22 01:10

fejese


\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?

like image 1
Kuba Avatar answered Oct 11 '22 01:10

Kuba