title: Reshaping data from a std::vector<double> into double** of specified dimensions using reinterpret_cast
body: <p>I have a <code>std::vector&lt;double&gt;</code> containing <code>M*N</code> values, and I'd like to reshape this into a <code>double**</code> which behaves like a <code>double[N][M]</code> multidimensional array. 
  These start and end points may seem strange, but they are unfortunately both decided by external libraries, so there's not much I can do about them. I'm asking this question to see if there's a way to accomplish this without simply copying all the data manually.</p>
  
  <p>I did read <a href="https://stackoverflow.com/questions/15283523/reshaping-a-1-d-array-to-a-multidimensional-array">this question, with an excellent answer</a>, but it has slightly different starting point - rather than going from <code>std::vector&lt;double&gt;</code> to <code>double**</code>, it goes from <code>double[]</code> to <code>double[][]</code>. I tried to understand what was going on there and apply the same principles to my case, but I can't get my code to work. How do I do this correctly?</p>
  
  <pre><code>const int M = 3;
  const int N = 2;
  std::vector&lt;double&gt; f = { 0, 1, 2, 3, 4, 5 };
  
  double* f1d = f.data();
  
  // compiles and doesn't crash
  // but f2d seems to be unitialized (at least f2d[1][1] is garbage)
  // also has the wrong type (double[][] rather than double**)
  double (&amp;f2d)[N][M] = reinterpret_cast&lt;double (&amp;)[N][M]&gt;(f1d);
  
  // segfaults when trying to access e.g. f2d[0][0]
  double** f2d = reinterpret_cast&lt;double**&gt;(f1d);
  </code></pre>
  
  <p>Eventually, I need to pass my data into a method which takes a <code>double**</code> parameter, so the following has to compile and run without problem:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  void test(int M, int N, double **arr) {
      for (int i = 0; i &lt; N; ++i) {
          for (int j = 0; j &lt; M; ++j) {
              std::cout &lt;&lt; arr[i][j] &lt;&lt; " ";
          }
          std::cout &lt;&lt; std::endl;
      }
  };
  
  int main() {
      const int M = 3;
      const int N = 2;
      std::vector&lt;double&gt; f = { 0, 1, 2, 3, 4, 5 };
  
      // whatever I need to do here to get f2d
  
      test(M, N, f2d);
      return 0;
  }
  </code></pre>
  
  <p>Expected output:</p>
  
  <pre><code>0 1 2 
  3 4 5
  </code></pre>