Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The lines:</p> <pre><code>for (int i = 0; i&lt;*row; i++) { for (int j = i+1; j&lt;*col; j++) { int temp = *(*(matrix + i) + j); *(*(matrix + i) + j) = *(*(matrix + j) + i); *(*(matrix + j) + i) = temp; } } </code></pre> <p>are the issue. The problem is that matrix is indexed by i then j, not j then i like you are doing in the second and third line in the while loop. Image that matrix is a 2x3 matrix, then you try to perform matrix[2][3] = matrix[3][2], but matrix[3][2] does not exist.</p> <p>It is best to go about simply initializing result directly in this loop:</p> <pre><code>for (int i = 0; i&lt;*row; i++) for (int j = 0; j&lt;*col; j++) result[j][i] = matrix[i][j]; </code></pre> <p>Then you can output like below, or delete matrix and reassign matrix to be result as you wish. My entire transpose function became the following code (row and col need not be pointers to int pass by value is just fine. Also accessing matrices should use array subscripts as it is nicer style):</p> <pre><code>void transpose(int **matrix, int row, int col) { // dynamically allocate an array int **result; result = new int *[col]; //creates a new array of pointers to int objects for (int i = 0; i &lt; col; i++) result[i] = new int[row]; // transposing for (int i = 0; i&lt;row; i++) for (int j = 0; j&lt;col; j++) result[j][i] = matrix[i][j]; //output resulting matrix for (int i = 0; i&lt;col; i++) { for (int j = 0; j&lt;row; j++) cout &lt;&lt; result[i][j] &lt;&lt; "\t"; cout &lt;&lt; endl; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload