+ 1

When should I put a '\0' to the end of a string or character array?

And what's '\0' means and used for? I'm confused about it when handling my homework about string.

10th Apr 2018, 4:49 PM
Matt Zhang
Matt Zhang - avatar
5 Antworten
+ 6
If you use char str[] = "test";, you automatically get 5 characters with '\0' as the last. If you wish to remove the 'e', you could do: str[1]=str[2];str[2]=str[3];str[3]='\0'; If your string is not terminated with '\0', cout << str; will keep printing until it finds one. However, you can always loop 3 times and print characters so it isn't required.
10th Apr 2018, 6:55 PM
John Wells
John Wells - avatar
+ 5
It means the array is a string
10th Apr 2018, 4:59 PM
Toni Isotalo
Toni Isotalo - avatar
+ 2
It’s used to tell the computer thats the end of the string
10th Apr 2018, 4:59 PM
TurtleShell
TurtleShell - avatar
+ 2
It was so that you could do for (char* it = str; *it != '\0'; ++it)
10th Apr 2018, 6:24 PM
Timon Paßlick
+ 2
Side note: This is more of a C than C++ question, still I guess it may have historical significance. By the way, in C++, prefer std::string for strings as you need not worry about null-termination (the '\0', lesson below). Since nobody mentioned it yet, and OP asked, '\0' is a null (equal to 0). A string ending in '\0' is called a null-terminated string. Historical value: In the older days, 0 was all a C function had to tell it had reached the end (preventing overflow) of a string without a user-supplied length. strlen is a good example here: Arrays of char are passed by reference and strlen counts from the start address until it encounters a zero. The value, like a newline, must be escaped, since '0' has an ASCII value of 48. QED: "ABC0" is 65, 66, 67, 48 "ABC\0" is 65, 66, 67, 0 I was going to get more in-depth, but that should cover it and the time's 00h47 where I live.
10th Apr 2018, 10:50 PM
non