title: Transposing a matrix using c++
body: <p>I want to write a program to transpose a n*n matrix, but the code output something wired. It did not transpose the matrix. suppose I want to transpose a matrix{(1,2,3), {4,5,6),(7,8,9)}, the result is basically the same as the original one with some strange behavior which I have no knowledge of.</p>
  
  <pre><code>#include&lt;iostream&gt;
  #include&lt;iomanip&gt;
  using namespace std;
  void transpose(int* p, int n);
  #define M 20
  int main()
  {
      int a[M][M];
      int n;      
      int* p;
      cout &lt;&lt; "The size of a matrix is: ";
      cin &gt;&gt; n;
      cout &lt;&lt; "Input a matrix: " &lt;&lt; endl;
      for (int i = 0; i &lt; n; i++)
          for (int j = 0; j &lt; n; j++)
              cin &gt;&gt; a[i][j];
      p = &amp;a[0][0];
      transpose(p, n);
      cout &lt;&lt; "Now, the matrix is: " &lt;&lt; endl;
      for (int i = 0; i &lt; n; i++)
      {
  
          for (int j = 0; j &lt; n; j++)
          {
              cout &lt;&lt; setw(4) &lt;&lt; a[i][j];
          }
          cout &lt;&lt; endl;
      }
      return 0;
  }
  
  void transpose(int* p, int n)
  {
      for (int i = 0; i &lt; n; i++)
      {
          for (int j = i; j &lt; n; j++)
          {
              int temp = *(p + i * n + j);
              *(p + i * n + j) = *(p + j * n + i);
              *(p + j * n + i) = temp;
          }
      }
  }
  </code></pre>