Transposing a matrix in C++ -
i'm writing programme transpose given matrix using allocated memory. function works perfect square matrix nxn (rows==cols) crashes mxn matrix (rows != cols). please help
void transpose(int **matrix, int *row, int *col) { // dynamically allocate array int **result; result = new int *[*col]; //creates new array of pointers int objects // check error if (result == null) { cout << "error allocating array"; exit(1); } (int count = 0; count < *col; count++) { *(result + count) = new int[*row]; } // transposing (int = 0; i<*row; i++) { (int j = i+1; j<*col; j++) { int temp = *(*(matrix + i) + j); *(*(matrix + i) + j) = *(*(matrix + j) + i); *(*(matrix + j) + i) = temp; } } (int = 0; i<*row; i++) { (int j = 0; j<*col; j++) { *(*(result + i) + j) = *(*(matrix + i) + j); cout << *(*(result + i) + j) << "\t"; } cout << endl; } }
the lines:
for (int = 0; i<*row; i++) { (int j = i+1; j<*col; j++) { int temp = *(*(matrix + i) + j); *(*(matrix + i) + j) = *(*(matrix + j) + i); *(*(matrix + j) + i) = temp; } }
are issue. problem matrix indexed j, not j doing in sec , 3rd line in while loop. image matrix 2x3 matrix, seek perform matrix[2][3] = matrix[3][2], matrix[3][2] not exist.
it best go initializing result straight in loop:
for (int = 0; i<*row; i++) (int j = 0; j<*col; j++) result[j][i] = matrix[i][j];
then can output below, or delete matrix , reassign matrix result wish. entire transpose function became next code (row , col need not pointers int pass value fine. accessing matrices should utilize array subscripts nicer style):
void transpose(int **matrix, int row, int col) { // dynamically allocate array int **result; result = new int *[col]; //creates new array of pointers int objects (int = 0; < col; i++) result[i] = new int[row]; // transposing (int = 0; i<row; i++) (int j = 0; j<col; j++) result[j][i] = matrix[i][j]; //output resulting matrix (int = 0; i<col; i++) { (int j = 0; j<row; j++) cout << result[i][j] << "\t"; cout << endl; } }
c++ matrix transpose
No comments:
Post a Comment