+ 1
what's wrong here?
i want to reverse matrix(strings to columns and columns to strings), but i can't fix the segmentation fault https://code.sololearn.com/c0Bns43hMZ8p/?ref=app
8 Réponses
+ 4
The problem came from attempt to access invalid row index in the <matrix> at line 7
swap( matrix[ i ], matrix[ n - i ] );
Here, when <i> was zero, <n> minus <i> will be the same as <n> itself. But valid index is only from 0 ~ <n> minus 1.
I still am not getting your intention clearly though. Are you swapping rows or columns or something else?
+ 4
It looks like you're trying on matrix transposition there. If you like, you can check the discussion about matrix transposition from stackoverflow (linked at bottom). There are explanations on how to transpose a matrix using various methods, even ones I rarely seen.
P.S. You can also browse SoloLearn's Code section for examples, make use of the search bar : )
https://stackoverflow.com/questions/16737298/what-is-the-fastest-way-to-transpose-a-matrix-in-c
+ 1
thanks, Ipang, i want to change matrix from for example
1 2 3
4 5 6
7 8 9
to
1 4 6
2 5 8
3 6 9
+ 1
thanks
+ 1
Take a look
https://code.sololearn.com/c4ub6UDd5mfz/?ref=app
+ 1
well done
+ 1
#include <iostream>
using namespace std;
void foo(int** matrix, int n, int m)
{
int** matrix2 = new int*[m];
for (int i = 0; i < m; ++i)
{
matrix2[i] = new int[n];
for (int j = 0; j < n; ++j)
{
matrix2[i][j] = matrix[j][i];
}
}
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
cout << matrix2[i][j] << " ";
}
cout << endl;
}
// Free memory
for (int i = 0; i < m; ++i)
{
delete[] matrix2[i];
}
delete[] matrix2;
}
int main()
{
int n, m;
cin >> n >> m;
int** matrix = new int*[n];
for (int i = 0; i < n; ++i)
{
matrix[i] = new int[m];
for (int j = 0; j < m; ++j)
{
matrix[i][j] = j + m * i + 1;
}
}
foo(matrix, n, m);
// Free memory
for (int i = 0; i < n; ++i)
{
delete[] matrix[i];
}
delete[] matrix;
return 0;
}
0
Ipang oh sorry, i made a mistake, check the code again please