Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The title of your question references C strings. C++ <code>std::string</code> objects are handled differently than <em>standard C</em> strings. <code>\0</code> is important when using C strings, and when I use the term <code>string</code> here, I'm referring to <em>standard C strings</em>.</p> <p><code>\0</code> acts as a string terminator in C. It is known as the <em>null character</em>, or <em>NUL</em>. It signals code that processes strings - standard libraries but also your own code - where the end of a string is. A good example is <code>strlen</code> which returns the length of a string.</p> <p>When you declare a constant string with:</p> <pre><code>const char *str = "JustAString"; </code></pre> <p>then the <code>\0</code> 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 <a href="http://en.cppreference.com/w/c/string/byte/strncpy">docs for strncpy</a>, which is used in your example, are a good illustration: <code>strncpy</code> copies over the null termination characters <strong>except</strong> in the case where the specified length is reached before the entire string is copied. Hence you'll often see <code>strncpy</code> combined with the <em>possibly redundant</em> assignment of a null terminator. <code>strlcpy</code> and <code>strcpy_s</code> were designed to address the potential problems that arise from neglecting to handle this case.</p> <p>In your particular example, <code>array[s.size()] = '\0';</code> is one such redundancy: since <code>array</code> is of size <code>s.size() + 1</code>, and <code>strncpy</code> is copying <code>s.size()</code> characters, the function will append the <code>\0</code>.</p> <p>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 <code>strncpy</code> the details are easily overlooked, leading to potential buffer overflows.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload