0
I’m learning better C++ for marathons and I’m starting to use more methods instead of doing everything on main(), I need to read an array but I’m having trouble doing it through a method because this matrix doesn’t exist after the call of the function to read the whole matrix, that is, when it arrives at the printMatriz() of the segmentationFault because the matrix no longer exists in this scope.
#include <iostream>
using namespace std;
void readMatriz(int **M, int n) {
M = new int *[n];
for (int i = 0; i < n; i++) {
M[i] = new int [n];
for (int j = 0; j < n; j++) {
cin >> M[i][j];
}
}
}
void printMatriz(int **M, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << M[i][j] << " ";
}
cout << endl;
}
}
int main() {
int n, **M;
cin >> n;
readMatriz(M, n);
printMatriz(M, n);
return 0;
}
Debugging the code I realize that I can call the function printMatriz() when I am still in the scope of readMatriz(), but outside it seems that the matrix no longer exists, which I find very strange because I am not passing value but reference.
If I take this part M = new int *[n]; which is in readMatriz() and move to main and code works perfectly and does not give segmentationFault.
Sorry some inconsistency is my first question posted here at Stackoverflow.