I’m trying to pass a user-defined array (defined here as matrix1) into a function (det) with the aim of calculating the determinant.
Any help would be appreciated, I’m sure there’s an easy way to do this, but my various attempts using pointers/vectors have been futile!
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int c, d;
int matrix1(int nS)
{
cout << "Enter the elements of first matrix: ";
int matrix1[10][10];
for (c = 0 ; c < nS ; c++ )
for (d = 0 ; d < nS ; d++ )
cin >> matrix1[c][d];
for (c = 0 ; c < nS ; c++ )
{
for (d = 0 ; d < nS ; d++ )
cout << matrix1[c][d] << "\t";
cout << endl;
}
}
int det(int nS, int matrix)
{
int det;
int iii;
for (iii = 0; iii < nS; iii++)
{
double a;
double b;
int c;
for (c = 0; c<nS; c++)
{
// cout << (iii+c)%nS << endl;
// cout << (nS-1) - (iii+c)%nS << endl;
int z = (iii+c)%nS;
cout << c << ", " << z << endl;
a *= matrix[c][z];
b *= matrix[c][(nS-1) - (iii+c)%nS];
}
det+= a-b;
}
cout << det << endl;
}
int main()
{
cout << "Enter the number of rows and columns of matrix: ";
int nS;
cin >> nS;
matrix1(nS);
det(nS, matrix1);
return 0;
}
You have to declare the array inside your main function for other functions to access it as well. An array declared inside a function other than main has a local scope on the stack and it gets destroyed as soon the function body gets executed.
That being said, you have two entities with the same name, a matrix array and a function. This wont compiler so make their names unique. Declare your matrix array in main like this.
Now pass it to your input function
matrix1like this.And your matrix function would be like this.
You can pass it to the
detfunction as well in a similar fashion. And it is better if you make the row and column numbers asconstso that you can change them later in your program easily.You can learn more on why the column number is passed and how a 2D array gets passed to a function in a similar answer here.
2D-array as argument to function