title: How does C++ handle vectors when passing from a function to main?
body: <p>I'm seeing strange behaviour in the output of a 'simple' function that generates the binary representation of an integer. I aim to use the function in another code, but first want to see it working by printing to the console. I first define the function dec2bin to take a number and the length of the required bitstring. After defining a vector that will be returned by the function, the vector is populated with the required binary values. In the main function, the vector is accessed and printed element-wise to the console. However, the output is incorrect unless I include an arbitrary cout statement within the vector populating for loop.</p>
  <p>The function is defined as follows:</p>
  <pre><code>vector&lt;int&gt; dec2bin(int N, int j){
      vector&lt;int&gt; myvec;
      myvec.push_back(N);
      for (int i = N-1; i &gt;= 0; i--) {
          int r = j &gt;&gt; i;
          if (r &amp; 1)
              myvec[N-i-1] = 1;
          else 
              myvec[N-i-1] = 0;
          //cout &lt;&lt; &quot; &quot;;
      }
      return myvec;
  }
  </code></pre>
  <p>My main function is:</p>
  <pre><code>int main(){
      int length = 8;
      int num = 15;
      vector&lt;int&gt; myvec = dec2bin(length,num);
      for (int j=0; j&lt;length; j++){cout &lt;&lt; myvec[j];}
      return 0;
  }
  </code></pre>
  <p>When the commented out line (cout &lt;&lt; &quot; &quot;) is included within the for loop the output is correct, with 00001111. Without that line (or with the line outside of the for loop) the output is incorrectly 00001141130.</p>
  <p>I have read various things about pointers and memory allocation, so expect this is where I am going wrong; however, I can't quite see how to incorporate those ideas into my own code. Any advice would be greatly appreciated, many thanks.</p>