title: How does C know the end of my string?
body: <p>I have a program in which I wanted to remove the spaces from a string. I wanted to find an elegant way to do so, so I found the following (I've changed it a little so it could be better readable) code <a href="http://www.daniweb.com/software-development/c/threads/21071/what-function-can-delete-a-space-in-a-string" rel="noreferrer">in a forum</a>:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>char* line_remove_spaces (char* line)
  {
      char *non_spaced = line;
      int i;
      int j = 0;
      for (i = 0; i &lt;= strlen(line); i++)
      {
          if ( line[i] != ' ' )
          {
              non_spaced[j] = line[i];
              j++;
          }
      }
      return non_spaced;
  }
  </code></pre>
  
  <p>As you can see, the function takes a string and, using the same allocated memory space, selects only the non-spaced characters. It works!</p>
  
  <p>Anyway, according to Wikipedia, a string in C is a "<a href="http://en.wikipedia.org/wiki/Null-terminated_string" rel="noreferrer">Null-terminated string</a>". I always thought this way and everything was good. But the problem is: we put no "null-character" in the end of the <code>non_spaced</code> string. And somehow the compiler knows that it ends at the last character changed by the "non_spaced" string. How does it know?</p>