Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '\0' mean?

Tags:

I can't understand what the '\0' in the two different place mean in the following code:

string x = "hhhdef\n"; cout << x << endl; x[3]='\0'; cout << x << endl; cout<<"hhh\0defef\n"<<endl; 

Result:

hhhdef

hhhef

hhh

Can anyone give me some pointers?

like image 793
halostack Avatar asked Jan 06 '13 15:01

halostack


People also ask

What is the meaning of '\ 0?

The null character '\0' (also null terminator ), abbreviated NUL , is a control character with the value zero . Its the same in C and objective C. The character has much more significance in C and it serves as a reserved character used to signify the end of a string ,often called a null-terminated string.

What is the meaning of '\ 0 in C++?

The \0 is treated as NULL Character. It is used to mark the end of the string in C. In C, string is a pointer pointing to array of characters with \0 at the end.

Why we use '\ 0 at the end of the string?

it is used to show that the string is completed.it marks the end of the string. it is mainly used in string type.by default string contain '\0\ character means it show the end of the character in string. end of the array contain ''\0' to stop the array memory allocation for string name.

What is the use of '\ 0 in C programming?

“\0” is the null termination character. It is used to mark the end of a string. Without it, the computer has no way to know how long a group of characters (string) goes. In C/C++ it looks for the Null Character to find the end of a string.


2 Answers

C++ std::strings are "counted" strings - i.e., their length is stored as an integer, and they can contain any character. When you replace the third character with a \0 nothing special happens - it's printed as if it was any other character (in particular, your console simply ignores it).

In the last line, instead, you are printing a C string, whose end is determined by the first \0 that is found. In such a case, cout goes on printing characters until it finds a \0, which, in your case, is after the third h.

like image 53
Matteo Italia Avatar answered Oct 27 '22 06:10

Matteo Italia


C++ has two string types:

The built-in C-style null-terminated strings which are really just byte arrays and the C++ standard library std::string class which is not null terminated.

Printing a null-terminated string prints everything up until the first null character. Printing a std::string prints the whole string, regardless of null characters in its middle.

like image 22
Konrad Rudolph Avatar answered Oct 27 '22 07:10

Konrad Rudolph