This does not happen by magic. You have in your code:

for (i = 0; i <= strlen(line); i++)
              ^^

The loop index i runs till strlen(line) and at this index there is a nul character in the character array and this gets copied as well. As a result your end result has nul character at the desired index.

If you had

for (i = 0; i < strlen(line); i++)
              ^^

then you had to put the nul character manually as:

for (i = 0; i < strlen(line); i++)
{
    if ( line[i] != ' ' )
    {
        non_spaced[j] = line[i];
        j++;
    }
}
// put nul character
line[j] = 0;
Answer from codaddict on Stack Overflow
🌐
Eskimo
eskimo.com › ~scs › cclass › notes › sx8.html
Chapter 8: Strings
Strings in C are represented by arrays of characters. The end of the string is marked with a special character, the null character, which is simply the character with the value 0. (The null character has no relation except in name to the null pointer. In the ASCII character set, the null character ...
Discussions

Why is a null character at the end of a string important
What do you mean you "declared the string." C has no string type, just arrays of characters. Unfortunately, unless you retain the size of the array somewhere, you won't know where the end is unless you put a null there. Note that arrays are only half-assed types in C. You can't assign them, and when they appear in function declarations the compiler silently replaces them with pointers to their first member. Essentially, every language in the world does strings one of two ways, either it puts some sentinal value (like a null) at the end or it explicitly stores the length somewhere. More on reddit.com
🌐 r/C_Programming
30
0
March 30, 2023
c - Array of char* should end at '\0' or "\0"? - Stack Overflow
The proper way to test for the ... in the string (i.e. spell it as "") since that will already include a null byte. ... Martin v. Löwis · 128k2020 gold badges205205 silver badges238238 bronze badges ... I do find it interesting that this problem has two answers that work, but neither is technically correct, and neither works for the reason the OP thinks they do. 2009-09-27T10:19:10.553Z+00:00 ... Well, technically '\0' is a character while "\0" ... More on stackoverflow.com
🌐 stackoverflow.com
Passing a pointer to indicate the end of a string?
Do some pointer math. Let's visualize it: Pos: 0123456 Str: Hello! Ptr: ^- Pointer The length of this string is 6 characters. So if we add 6 to the pointer, then the pointer points to the terminating character (\0): Pos: 0123456 Str: Hello! Ptr: ^- Pointer Off by one! So we just fix it by subtracting it by one, so it points to the last character in the string: 0123456 Hello! ^- Pointer So the formular is str + str_len - 1, where str is the pointer to the string and str_len is the length of the string. Let's test it with some code: #include #include int main() { char str[] = "Hello!"; printf("Normal: %s\n", str); printf("Last: %s\n", str + strlen(str) - 1); return 0; } Output: Normal: Hello! Last: ! Yep, it works! More on reddit.com
🌐 r/C_Programming
26
11
March 29, 2016
Why are strings in C++ usually terminated with '\0'? - Stack Overflow
I figured out that they are not ... an empty character. 2017-03-07T16:04:07.717Z+00:00 ... @CaptainDaVinci They're not necessarily terminated since the length is stored internally. If you call c_str() then you'll get a properly terminated buffer, but only because you asked nicely. 2017-12-11T18:35:52.26Z+00:00 ... @tadman is there an efficient way for std::string to implement c_str() other than by always keeping a NUL-terminator byte at the end of the ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
University of Texas
farside.ph.utexas.edu › teaching › 329 › lectures › node21.html
Character strings
Here, 'f' represents the character ``f'', etc., and '\0' represents the so-called null character (ASCII code 0), which is used in C to signal the termination of a character string. The null character is automatically added to the end of any character string enclosed in double quotes.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › strings-in-c
Strings in C - GeeksforGeeks
2 weeks ago - A string in C is an array of characters terminated by a null character '\0'. The null character '\0' marks the end of the string.
Top answer
1 of 6
31

I would end it with NULL. Why? Because you can't do either of these:

array[index] == '\0'
array[index] == "\0"

The first one is comparing a char * to a char, which is not what you want. You would have to do this:

array[index][0] == '\0'

The second one doesn't even work. You're comparing a char * to a char *, yes, but this comparison is meaningless. It passes if the two pointers point to the same piece of memory. You can't use == to compare two strings, you have to use the strcmp() function, because C has no built-in support for strings outside of a few (and I mean few) syntactic niceties. Whereas the following:

array[index] == NULL

Works just fine and conveys your point.

2 of 6
8

According to the C99 spec,

  • NULL expands to a null pointer constant, which is not required to be, but typically is of type void *
  • '\0' is a character constant; character constants are of type int, so it's equivalen to plain 0
  • "\0" is a null-terminated string literal and equivalent to the compound literal (char [2]){ 0, 0 }

NULL, '\0' and 0 are all null pointer constants, so they'll all yield null pointers on conversion, whereas "\0" yields a non-null char * (which should be treated as const as modification is undefined); as this pointer may be different for each occurence of the literal, it can't be used as sentinel value.

Although you may use any integer constant expression of value 0 as a null pointer constant (eg '\0' or sizeof foo - sizeof foo + (int)0.0), you should use NULL to make your intentions clear.

🌐
Sololearn
sololearn.com › en › Discuss › 1207298 › when-should-i-put-a-0-to-the-end-of-a-string-or-character-array
When should I put a '\0' to the end of a string or character ...
April 10, 2018 - Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
Find elsewhere
🌐
W3Schools
w3schools.com › c › c_strings.php
C Strings
This is known as the "null terminating character", and must be included when creating strings using this method. It tells C that this is the end of the string.
🌐
Wikipedia
en.wikipedia.org › wiki › Null-terminated_string
Null-terminated string - Wikipedia
March 25, 2025 - This allows the string to contain NUL and made finding the length need only one memory access (O(1) (constant) time), but limited string length to 255 characters. C designer Dennis Ritchie chose to follow the convention of null-termination to avoid the limitation on the length of a string and because maintaining the count seemed, in his experience, less convenient than using a terminator.
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_strings.htm
Strings in C
A string in C is a one-dimensional array of char type, with the last character in the array being a "null character" represented by '\0'. Thus, a string in C can be defined as a null-terminated sequence of char type values.
🌐
Techcrashcourse
techcrashcourse.com › 2015 › 05 › c-programming-strings.html
String in C Programming
String in C programming language is a one-dimensional array of characters which is terminated by a null character('\0'). A character array which is not null terminated is not a valid C string.
🌐
Weber State University
icarus.cs.weber.edu › ~dab › cs1410 › textbook › 8.Strings › c_string.html
8.2. C-Strings
C-string, defining C-strings, creating ... with one additional feature: they mark the end of the string text with a special character called the null termination character....
🌐
University of Kent
cs.kent.edu › ~durand › CS2 › Notes › 01_Intro › c2_stringCstyle.html
C-Style Strings
If the terminating null-character appears in src string before num character have been appended, the function appends the null-character to dest and ends. The terminating null character in dest is overwritten by the first character of src. The resulting string includes a null-character at end. Parameters. ... Pointer to a null-terminated string with enough space allocated to contain src plus num characters.
🌐
Reddit
reddit.com › r/c_programming › passing a pointer to indicate the end of a string?
r/C_Programming on Reddit: Passing a pointer to indicate the end of a string?
March 29, 2016 -

Strings are correctly passed to printf() as a char * to the first character of the string. Normally, printf() goes until it finds a null byte. Is there a way to supersede that normal search for the null byte, and feed a pointer to the last character in printf?

Top answer
1 of 5
48

The title of your question references C strings. C++ std::string objects are handled differently than standard C strings. \0 is important when using C strings, and when I use the term string in this answer, I'm referring to standard C strings.

\0 acts as a string terminator in C. It is known as the null character, or NUL, and standard C strings are null-terminated. This terminator signals code that processes strings - standard libraries but also your own code - where the end of a string is. A good example is strlen which returns the length of a string: strlen works using the assumption that it operates on strings that are terminated using \0.

When you declare a constant string with:

const char *str = "JustAString";

then the \0 is appended automatically for you. In other cases, where you'll be managing a non-constant string as with your array example, you'll sometimes need to deal with it yourself. The docs for strncpy, which is used in your example, are a good illustration: strncpy copies over the null terminator character except in the case where the specified length is reached before the entire string is copied. Hence you'll often see strncpy combined with the possibly redundant assignment of a null terminator. strlcpy and strcpy_s were designed to address the potential problems that arise from neglecting to handle this case.

In your particular example, array[s.size()] = '\0'; is one such redundancy: since array is of size s.size() + 1, and strncpy is copying s.size() characters, the function will append the \0.

The documentation for standard C string utilities will indicate when you'll need to be careful to include such a null terminator. But read the documentation carefully: as with strncpy the details are easily overlooked, leading to potential buffer overflows.

2 of 5
16

Why are strings in C++ usually terminated with '\0'?

Note that C++ Strings and C strings are not the same.
In C++ string refers to std::string which is a template class and provides a lot of intuitive functions to handle the string.
Note that C++ std::string are not \0 terminated, but the class provides functions to fetch the underlying string data as \0 terminated c-style string.

In C a string is collection of characters. This collection usually ends with a \0.
Unless a special character like \0 is used there would be no way of knowing when a string ends.
It is also aptly known as the string null terminator.

Ofcourse, there could be other ways of bookkeeping to track the length of the string, but using a special character has two straight advantages:

  • It is more intuitive and
  • There are no additional overheads

Note that \0 is needed because most of Standard C library functions operate on strings assuming they are \0 terminated.
For example:
While using printf() if you have an string which is not \0terminated then printf() keeps writing characters to stdout until a \0 is encountered, in short it might even print garbage.

Why should we use '\0' here?

There are two scenarios when you do not need to \0 terminate a string:

  • In any usage if you are explicitly bookkeeping length of the string and
  • If you are using some standard library api will implicitly add a \0 to strings.

In your case you already have the second scenario working for you.

array[s.size()] = '\0';

The above code statement is redundant in your example.

For your example using strncpy() makes it useless. strncpy() copies s.size() characters to your array, Note that it appends a null termination if there is any space left after copying the strings. Since arrayis of size s.size() + 1 a \0 is automagically added.

🌐
Cprogramming
cboard.cprogramming.com › c-programming › 108449-check-end-string.html
check end of string
October 23, 2008 - You can use strrchr(a, '\n') to locate the the last occurence of a newline in the string that's stored in the array but strchr(a, '\n') ought to do the job because the standard C lib ensures that each line is terminated by a newline so there can't be multiple occurrences of the newline character ...
🌐
Quora
quora.com › Why-does-a-string-in-C-end-with-0-but-not-in-arrays-What-is-the-reason-for-that
Why does a string in C end with '/0' but not in arrays? What is the reason for that? - Quora
Answer: There are many different reasons behind it When you end a array of string you need to add /0 because by this only the library knows where the string ends. And with the end of string knowledge you can perform certain actions on that string ...
🌐
Reddit
reddit.com › r/cpp_questions › why are null terminators needed to signify the end of a string when arrays don’t have anything to signify the end of it?
r/cpp_questions on Reddit: Why are null terminators needed to signify the end of a string when arrays don’t have anything to signify the end of it?
August 19, 2023 -

All strings inherently have ‘\0’ at the end to know when the end of the string is.

However, arrays don’t have anything like this. You can keep accessing indexes to infinity and it’ll output something.

So I’m wondering, exactly why are null terminators needed in strings if nothing similar like is applied to c++ arrays?

What’s the benefit?

TLDR: why are null terminators needed in strings but there’s nothing to signify the end of an array?

Top answer
1 of 13
35
All strings inherently have ‘\0’ at the end to know when the end of the string is. Notably its just a convention. 60 years ago the C language decided that arrays should not be first class constructs in the language. That is why raw arrays decay into pointers and you have to manually pass around their size (at least in C, in C++ you can capture it as a template parameter). However you didnt want to pass around the size of a string all the time. As a result using a null terminator for character strings was a "good" choice. Essentially they didnt want to treat arrays as objects, but wanted to use character arrays as objects. All C-strings and std::string (which wants to be usable with C interfaces) have this. However, a std::string_view can view a character array without a null terminator - because it internally stores the size/end. However, arrays don’t have anything like this. You can keep accessing indexes to infinity and it’ll output something. No you cant. Accessing an array out of bounds is undefined behaviour. Formally, you cannot reason about it. It may "appear to work" (since the produced assembly will just do a simple index calculation). However, if the memory you are trying to access doesnt belong to your program, the OS will terminate your program with a segfault. If you write out of bounds, you may trash your stack, or you may also get a segfault. there’s nothing to signify the end of an array? Another important point here is the type. With characters, we can easily chose a non-printable, special value as the sentinel value to signal the end. But what could that sentinel value be for e.g. int. 0? Surely not. We want to be able to store zeros in our arrays. INT_MAX? But what if I actually want to store that value? Essentially there is no possible sentinal value. This becomes even more obvious when the type isnt fundamental.
2 of 13
9
std::string doesn't actually use the NULL terminator. It contains its length as a typical member variable. However, it does ensure its underlying data is NULL terminated for compatibility with i.e C-style APIs via c_str(). And... if I provided you a library using std::string as parameters, your C++ std::string (from i.e MSVC) might have a different size / layout to my std::string (from i.e MINGW). C++ does not traditionally have a stable binary ABI. Instead by extracting and passing around the raw NULL terminated char*, we can sidestep this. This is why many C++ libraries take in raw C-style strings.