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 OverflowThis 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;
Others have answered your question already, but here is a faster, and perhaps clearer version of the same code:
void line_remove_spaces (char* line)
{
char* non_spaced = line;
while(*line != '\0')
{
if(*line != ' ')
{
*non_spaced = *line;
non_spaced++;
}
line++;
}
*non_spaced = '\0';
}
Videos
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?
Stupid Doubt maybe but, still one that makes me wanna rage quit it, can someone please tell me why is there a null character at the end of a string, but not at the end of a usual integer array? like why is a char array special and needs a char to let it know of the end of it. or why the usual array is smarter in knowing where it ends. Thanks in advance
I get that it marks the end of the string, but if I have the size with me when I declared the string what is the use of it. Plus if it’s so important why don’t int arrays have a null char at the end. The only reason I can think of is to output it into the terminal without going over the limit but I’m not sure if that’s the only reason or if it’s even a right reason
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?