title: Cast Array to Matrix in C/C++?
body: <p>If I have a function which internally uses a 3x3 matrix, but due to API limitations must pass it a contiguous array of nine elements, is there a way to essentially cast an array to a 2d array?</p>
  
  <p>The following approach doesn't work, but hopefully it conveys what I'm trying to do.</p>
  
  <p>I'm aware that packages like Eigen make this trivial, but unfortunately it's not an option for me in this case.</p>
  
  <pre><code>void transpose_3x3( double x[3][3] ) {
      ...
  }
  
  void foo( double x[9], double y[3][3] ) {
  
      transpose_3x3(y)  // OK    
  
      double *my_x[3][3] = &amp;x[0];
  
      transpose_3x3(&amp;my_x);  // How?
  
  }
  </code></pre>
  
  <p><strong>Edit</strong></p>
  
  <p>Thanks to Daniel for showing me the correct target for a cast, I was able to use the C++ reinterpret_cast function to accomplish this.  While the union and memcpy solutions work, a single explicit cast seems to be the most straightforward solution, IMHO.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  void print_matrix( double x[3][3] ) {
  
      for(unsigned int i=0; i&lt; 3; i++) {
          for(unsigned int j=0; j&lt;3; j++) {
              std::cout &lt;&lt; x[i][j] &lt;&lt; "  ";
          }
          std::cout &lt;&lt; std::endl;
      }
  }
  
  int main() {
  
      double a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9};    
      double (*b)[3] = reinterpret_cast&lt;double (*)[3]&gt;(a);  
  
      print_matrix(b);
      return 0;
  }
  </code></pre>