Here you will get C and C program to find inverse of a matrix. Write a program in C to find the minor of every elements of a square matrix of any order. The order of the square matrix should be entered by the user. Reply ↓ paulao October 25, 2017. What is the function of the mode in the code.
I'm writing a program to transpose a given matrix using allocated memory. The function works perfect with square matrix NxN (rowscols) but it crashes with MxN matrix (rows != cols). Please help
ForceBru22.3k88 gold badges3535 silver badges5858 bronze badges
CasperCasper82355 gold badges2121 silver badges4545 bronze badges
2 Answers
The lines:
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.
It is best to go about simply initializing result directly in this loop:
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):
pippin1289pippin12894,10522 gold badges1515 silver badges3333 bronze badges
You are trying to transpose matrix 'in place' :
((matrix + i) + j) = ((matrix + j) + i);
you shouldn't do this. If count of columns is greater then count of rows, allocated for
matrix
, you'll read and write non-allocated memory.IMHO, It would be better to store whole matrix in continuous memory. Not in different pieces. In this manner the code would look like this:
The only minus of this allocation, that you can't address an element like
matrix[ i ][ j ]
but only matrix[ i + col + j ]
. Pluses are: 1) easy to allocate/deallocate memory (just matrix = new int[ col * row ]
and delete [] matrix
) 2) a little bit faster access to elements (because of continuous location of them)At the end, I think, that it would be the best way to look at
std::vector
. If you want, I can show you, how will you function look with vectorborisbnborisbn