title: Memory hack to transpose matrix corrupts stack, C++
body: <p>I need to implement a matrix transpose procedure in C++.
  The problem is the signature, the function has to be called like this:</p>
  
  <pre><code>transpose(in_mat[0][0], n, m, out_mat[0][0])
  </code></pre>
  
  <p>where n and m are the dimensions.
  All values are doubles, both the matrices and the dimensions.</p>
  
  <p>Since the code is automatically generated, I can't fix this.</p>
  
  <p>My workaround looks like this:</p>
  
  <pre><code>void transpose(double&amp; in_mat, const double _n, const double _m, double&amp; out_mat)
  {
      int n = _n, m = _m;
      double* in_pointer= &amp;in_mat;
      double* out_pointer= &amp;out_mat;
      for (int i = 0; i &lt; n; i++) {
          for (int j = 0; j &lt; m; j++) {
              *(out_pointer+(j*n+i)) = *(in_pointer+(i*m + j));
          }
      }
  }
  </code></pre>
  
  <p>It works fine.
  I've constructed a test case with two matrices of different width and height. One is filled with random numbers, the other is filled with zeros. Then the transpose procedure is called and the two matrices are compared.
  The functionality is correct.</p>
  
  <p>But it corrupts the stack. When run in Visual Studio 2015 there is a warning</p>
  
  <blockquote>
    <p>Run-Time Check Failure #2 - Stack around the variable 'in_mat' was corrupted.</p>
  </blockquote>
  
  <p>What did I do wrong ? Why is the stack corrupted ?
  Code after the invocation of transpose works correctly.</p>
  
  <p>EDIT:</p>
  
  <p>Here is the complete setup:</p>
  
  <pre><code>#include &lt;random&gt;
  #include &lt;iostream&gt;
  
  void transpose(double&amp; in_mat, const double _n, const double _m, double&amp; out_mat)
  {
      int n = _n, m = _m;
      double* in_pointer = &amp;in_mat;
      double* out_pointer = &amp;out_mat;
      for (int i = 0; i &lt; n; i++) {
          for (int j = 0; j &lt; m; j++) {
              *(out_pointer+(j*n+i)) = *(in_pointer+(i*m + j));
          }
      }
  }
  
  
  int main()
  {
  
      double in_mat[5][4];
      double out_mat[4][5];// assign matrix
  
      for (int i = 0; i &lt; 4; i++) {
          for (int j = 0; j &lt; 5; j++) {
              in_mat[i][j] = std::rand();
              out_mat[j][i] = 0;
          }
      }
  
      double n = 5;
      double m = 4;
  
      transpose(in_mat[0][0], n, m, out_mat[0][0]);
  
      for (int i = 0; i &lt; n; i++) {
          for (int j = 0; j &lt; m; j++) {
              if (in_mat[i][j] - out_mat[j][i]&gt;0.0001) {
                  std::cout &lt;&lt; "code is broken" &lt;&lt; std::endl; //never reached
              }
          }
      }
      std::cout &lt;&lt; "finished" &lt;&lt; std::endl;
  }
  </code></pre>