Transpose 2 2d dynamic array
Oct 6, 2016 at 4:00pm UTC
I´m writing a void function to transpose a matrix and this is what I have:
Last edited on Oct 6, 2016 at 10:30pm UTC
Oct 6, 2016 at 4:44pm UTC
Have a look at the output of this code. I think you will find that your matrix is transposed but the result is last when you delete the temporary "trans" variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include <iostream>
using namespace std;
int ** myArray;
void print(int ** arr, int row, int col)
{
for (int y=0; y < row; y++)
{
for (int x=0; x < col; x++) cout << arr[x][y];
cout << endl;
}
}
void transpose(int ** arr, int row, int col)
{
int ** trans=new int *[col];
for (int i=0; i < col; i++)
{
trans[i]=new int [row];
}
for (int i=0; i < col; i++)
{
for (int j=0; j < row; j++)
{
trans[i][j]=arr[j][i];
}
}
print(trans, 2, 2);
for (int i=0; i < col; i++)
{
delete [] trans[i];
}
delete [] trans;
}
int main(int argc, char ** argv)
{
int ** myArray=new int *[2];
for (int i=0; i < 2; i++)
{
myArray[i]=new int [2];
}
myArray[0][0] = 0;
myArray[0][1] = 1;
myArray[1][0] = 2;
myArray[1][1] = 3;
print(myArray, 2, 2);
cout << endl;
transpose(myArray, 2, 2);
cout << endl;
print(myArray, 2, 2);
return 0;
}
Topic archived. No new replies allowed.