I am trying to transpose a matrix with pointer-to-pointer in c++ but there is an error: "segmentation fault ('core' dumped)". I tried to find the error on forums and figured out that in matrixTrans function, the 'puntero_trans = new int *[nCol];' line and the for loop next to it, I had to move to getData function. I really do not know why this happens. Thanks for your time. My code below:
#include <iostream>
void getData();
void matrixTrans(int **, int **,int, int);
void showData(int **, int, int);
//Global variables
int **puntero_matrix = nullptr, **puntero_trans;
int nRaws, nCol;
int main() {
getData();
matrixTrans(puntero_matrix,puntero_trans,nRaws,nCol);
showData(puntero_trans, nRaws,nCol);
//Flushing memory...
for (int i = 0; i < nRaws; ++i) {
delete[] puntero_matrix[i];
}
for (int i = 0; i < nCol; ++i) {
delete[] puntero_trans[i];
}
delete[] puntero_matrix;
delete[] puntero_trans;
std::cin.get();
return 0;
}
void getData() {
std::cout << "Please enter the number of raws:"; std::cin >> nRaws;
std::cout << "Please enter the number of columns: "; std::cin >> nCol;
puntero_matrix = new int* [nRaws];
for (int i = 0; i < nRaws; ++i) {
puntero_matrix[i] = new int[nCol];
}
for (int i = 0; i < nRaws; ++i) {
for (int j = 0; j < nCol; ++j) {
std::cout << "Please enter value for [" << i << "][" << j << "]: "; std::cin >> *(*(puntero_matrix + i) + j);
}
}
}
void matrixTrans(int **puntero_matrix, int **puntero_trans, int nRaws, int nCol) {
puntero_trans = new int *[nCol];
for (int i = 0 ; i < nCol; ++i) {
puntero_trans[i] = new int[nRaws];
}
for (int i = 0; i < nRaws; ++i) {
for (int j = 0; j < nCol; ++j) {
*(*(puntero_trans + j) + i) = *(*(puntero_matrix + i) + j);
}
}
}
void showData(int **puntero_trans,int nRaws,int nCol) {
for (int i = 0; i < nCol; ++i) {
for (int j = 0; j < nRaws; ++j) {
std::cout << *(*(puntero_trans + i) + j) << " ";
}
std::cout << std::endl;
}
}