title: Pointers vs vectors for arrays c++
body: <p>In the case I am creating an 'array' on stack in c++, is it better to initialise an empty vector with a reserved number of elements and then pass this to a function like <code>foo()</code> as a reference as below. Or is it better to set an array <code>arrb</code> of size <code>nelems</code>, then using a pointer <code>p_arrb</code> to the address of the first element increment the pointer and assign some value?</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
   
  void foo(std::vector&lt;int&gt;&amp; arr){
      int nelems = arr.capacity();    
      
      for (int i = 0; i &lt; nelems; i++){
          arr[i] = i;
      }
  
  }
  
  
  int main()
  {
      
      int nelems; 
      std::cout &lt;&lt; &quot;Type a number: &quot;; // Type a number and press enter
      std::cin &gt;&gt; nelems; 
  
      std::vector&lt;int&gt; arr;
      arr.reserve(nelems); // Init std lib vector
      foo(arr);
      
      int arrb[nelems];
      int* p_arrb = &amp;(arrb[0]);  // pointer to arrb
      
      for (int i = 0; i &lt; nelems; i ++){
          *(p_arrb++) = i;  // populate using pointer
      }
      p_arrb -= nelems; // decrement pointer
  
      return 0;
  }
  
  </code></pre>
  <p>It seems people prefer the use of vector as it is standardised and easier to read? Apart from that, is there any performance benefit to using vector instead of a basic pointer in this case where I do not need to change the size of my vector/array at any point in the code?</p>