Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Yes, this is fine so long as the type of the pointer matches what's actually being pointed to in the array. By incrementing a pointer you are performing pointer arithmetic.</p> <p>It may be interesting to note that because iterators in the Standard Library are written to look &amp; feel like pointers in many ways, and all the Standard Library algorithms take iterators specified as template parameters, it is legal and well-defined to use these algorithms with raw pointers as well. For example, this is perfectly legitimate, even with your pointers:</p> <pre><code>const size_t num_data = sizeof(data)/sizeof(data[0]); std::copy( &amp;data[0], &amp;data[num_data], ostream_iterator&lt;QString&gt;(cout,"\n") ); </code></pre> <p>...assuming of course you have implemented <code>operator&lt;&lt;</code> for a <code>QString</code> object.</p> <p>Now, all this being said, take a look at this:</p> <pre><code>QString data[100]; </code></pre> <p>The <code>100</code> here is what's called a <a href="http://en.wikipedia.org/wiki/Magic_number_%28programming%29" rel="nofollow">Magic Number</a>. The use of Magic Numbers is widely considered to be an <a href="http://en.wikipedia.org/wiki/Anti-pattern" rel="nofollow">anti-pattern</a>, or a bad practice. Ask yourself a couple questions:</p> <ol> <li>How do you know that 100 elements will be enough?</li> <li>If you don't need 100 elements, are you being wasteful?</li> <li>If you need more than 100 elements, will your program crash?</li> </ol> <p>It's best to avoid using magic numbers wherever you can. Your choice of <code>100</code> here is arbitrary. It would be better to use a collection type that grows and shrinks as you add and remove objects. <code>std::vector</code> is a good place to start:</p> <pre><code>std::vector&lt;QString&gt; data; </code></pre> <p>Now you can add items:</p> <pre><code>data.push_back( ... ); </code></pre> <p>...remove them, and iterate easily, using iterators:</p> <pre><code>std::copy( data.begin(), data.end(), ostream_iterator&lt;QString&gt;(cout,"\n") ); </code></pre>
 

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