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
🌐
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.
🌐
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.
🌐
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.
🌐
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 ...
🌐
Weber State University
icarus.cs.weber.edu › ~dab › cs1410 › textbook › 8.Strings › c_string.html
8.2. C-Strings
C-Strings are character arrays with one additional feature: they mark the end of the string text with a special character called the null termination character. The null termination character or null terminator is the character equivalent of zero, which C++ denotes with the escape sequence ...
🌐
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 ...
Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › Null-terminated_string
Null-terminated string - Wikipedia
March 25, 2025 - In computer programming, a null-terminated string is a character string stored as an array containing the characters and terminated with a null character (a character with an internal value of zero, called "NUL" in this article, not same as the glyph zero). Alternative names are C string, which ...
🌐
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.
🌐
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?

🌐
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 ...
🌐
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 array? | Sololearn: Learn to code for FREE!
April 10, 2018 - 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.
🌐
Cplusplus
cplusplus.com › reference › string › string › end
std::string::end
Returns an iterator pointing to the past-the-end character of the string. The past-the-end character is a theoretical character that would follow the last character in the string. It shall not be dereferenced.
🌐
Cppreference
en.cppreference.com › w › cpp › string › basic_string › end
std::basic_string<CharT,Traits,Allocator>::end, std::basic_string<CharT,Traits,Allocator>::cend - cppreference.com
Returns an iterator to the character following the last character of the string. This character acts as a placeholder, attempting to access it results in undefined behavior. ... Iterator to the character following the last character. ... #include <algorithm> #include <iostream> #include <iterator> ...
🌐
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.
🌐
GitHub
github.com › portfoliocourses › c-example-code › blob › main › endswith.c
c-example-code/endswith.c at main · portfoliocourses/c-example-code
if (end_length > string_length) return false; · // check the characters at the end of string to see if any of them do no match · // the characters in the end string, if any do no not, the string does not · // end with the end string, and we can return false ·
Author   portfoliocourses
🌐
Learn C
learnc.net › home › learn c programming › c string
C String
April 13, 2025 - Therefore, a string in C is an array of characters. To mark the end of a string, C uses a special character '\0'. The '\0' is called the null character.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › string-functions-in-c
C String Functions - GeeksforGeeks
July 26, 2025 - C language provides various built-in functions that can be used for various operations and manipulations on strings. These string functions make it easier to perform tasks such as string copy, concatenation, comparison, length, etc. The <string.h> header file contains these string functions. The strlen() function is used to find the length of a string.