I have an assignment to find the transpose of a matrix (in c++) only using array indices. My main calls the function indexTranspose, but I cannot figure out why when I print the array inside the function the output is correct, but when I print it out in the main the matrix is not updated. The matrix is a text file full of 9 random ints.
#include <iostream>
#include <fstream>
using namespace std;
//function declarations
void printMatrix(int m[][3]);
void indexTranspose(int n[3][3]);
//void pointerTranspose(int m[][3]);
//begin main
int main() {
int m[3][3];
ifstream values("matrix.txt");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
values >> m[i][j];
printMatrix(m);
indexTranspose(m);
printMatrix(m);
/*pointerTranspose(m);
printMatrix(m);
*/
} //end main
void printMatrix(int m[][3]) {
for (int i = 0; i < 3; i++) {
cout << "[ ";
for (int j = 0; j < 3; j++)
cout << m[i][j] << " ";
cout << "]" << endl;
}
cout <<endl;
}
void indexTranspose (int n[][3]) {
cout << "Transposing the matrix using indices..." <<endl;
int temp[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
temp[j][i] = n[i][j];
}
n = temp;
cout << "Printing n"<< endl;
printMatrix(n);
}
The output I get when I run this function is the original matrix, followed by the transpose (printed out inside the function), and then the original again. I am not sure why the transpose function only updates the array locally instead of modifying the array in the main as well.
std::arrayinstead.n = temp;-- This does do what you think it does. Use standard containers, where=works as intended.typedef std::array<std::array<int, 3>> Matrix, declare your 2d matrix like this, passMatrixby reference, and then things will magically work.