Friend Functions. 1) Friend of the class can be member of some other class. 2) Friend of one class can be friend of another class or all the classes in one program, such a friend is known as GLOBAL FRIEND. 3) Friend can access the private or protected members of the class in which they are declared to be friend.
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
CasperCasper
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):
pippin1289pippin1289
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