Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to work with null pointers in a std::vector
    primarykey
    data
    text
    <p>Say I have a vector of null terminates strings some of which may be null pointers. I don't know even if this is legal. It is a learning exercise.<br> Example code<br></p> <pre><code>std::vector&lt;char*&gt; c_strings1; char* p1 = "Stack Over Flow"; c_strings1.push_back(p1); p1 = NULL; // I am puzzled you can do this and what exactly is stored at this memory location c_strings1.push_back(p1); p1 = "Answer"; c_strings1.push_back(p1); for(std::vector&lt;char*&gt;::size_type i = 0; i &lt; c_strings1.size(); ++i) { if( c_strings1[i] != 0 ) { cout &lt;&lt; c_strings1[i] &lt;&lt; endl; } } </code></pre> <p>Note that the size of vector is 3 even though I have a NULL at location <code>c_strings1[1]</code><br> <strong>Question</strong>. How can you re-write this code using <code>std::vector&lt;char&gt;</code> What exactly is stored in the vector when you push a null value? <br><br> <strong>EDIT</strong><br> The first part of my question has been thoroughly answered but not the second. Not to my statisfaction at least. I <strong>do</strong> want to see usage of <code>vector&lt;char&gt;</code>; not some nested variant or <code>std::vector&lt;std::string&gt;</code> Those are familiar. So here is what I tried ( hint: it does not work) <br></p> <pre><code>std::vector&lt;char&gt; c_strings2; string s = "Stack Over Flow"; c_strings2.insert(c_strings2.end(), s.begin(), s.end() ); // char* p = NULL; s = ""; // this is not really NULL, But would want a NULL here c_strings2.insert(c_strings2.end(), s.begin(), s.end() ); s = "Answer"; c_strings2.insert(c_strings2.end(), s.begin(), s.end() ); const char *cs = &amp;c_strings2[0]; while (cs &lt;= &amp;c_strings2[2]) { std::cout &lt;&lt; cs &lt;&lt; "\n"; cs += std::strlen(cs) + 1; } </code></pre>
    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.
 

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