+ 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

14th Jun 2023, 10:48 AM
marat
marat - avatar
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?
14th Jun 2023, 11:07 AM
Ipang
+ 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
14th Jun 2023, 12:00 PM
Ipang
+ 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
14th Jun 2023, 11:14 AM
marat
marat - avatar
+ 1
thanks
14th Jun 2023, 12:01 PM
marat
marat - avatar
15th Jun 2023, 2:51 AM
Jeremy Ed
Jeremy Ed - avatar
+ 1
well done
15th Jun 2023, 5:53 AM
marat
marat - avatar
+ 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; }
15th Jun 2023, 7:49 AM
Vaibhav
Vaibhav - avatar
0
Ipang oh sorry, i made a mistake, check the code again please
14th Jun 2023, 11:26 AM
marat
marat - avatar