First of all, I made this class.
class Matrix
{
public:
double ele[4][4];
int numOfRow;
int numOfColumns;
public:
Matrix() {
numOfRow = 0;
numOfColumns = 0;
ele[4][4] = 0;
}
Matrix(double mat[][4], int Row, int Col) {
numOfRow = Row;
numOfColumns = Col;
for (int i = 0; i < numOfRow; i ) {
for (int j = 0; i < numOfColumns; j ) {
ele[i][j] = mat[i][j];
}
}
}
Matrix Add(Matrix m) {
Matrix output;
for (int i = 0; i < numOfRow; i ) {
for (int j = 0; j < numOfColumns; j ) {
output.ele[i][j] = ele[i][j] m.ele[i][j];
}
}
return output;
}
Matrix Subtract(Matrix m);
Matrix Multiply(Matrix m);
Matrix Transpose(void);
};
This is part of the main function. In this way, I'm going to bring up the values of the txt files that I've already made in matA
and matB
and replace them. It's just a process of putting numbers in.
double matA[4][4];
for (int i = 0; i < RowA; i ) {
for (int j = 0; j < ColA; j ) {
fscanf(fpInput, "%lf", &matA[i][j]);
}
}
double matB[4][4];
for (int i = 0; i < RowB; i ) {
for (int j = 0; j < ColB; j ) {
fscanf(fpInput, "%lf", &matB[i][j]);
}
}
And we substitute matrixA
and matrixB
class objects, respectively.
Matrix matrixA(matA, RowA, ColA);
Matrix matrixB(matB, RowB, ColB);
I tried substitute Value obtained by 'Add' function into class object called matrixO
. but, The substituted values did not work smoothly. For example, if matrixA
contains (1, 2, 3)
in order and matrixB
has (4, 5, 6)
, then the 'add function' requires that the array of matrixO
contains (5, 7, 9)
, but it does not. The value of the matrixO.ele
is not output at all.
Matrix matrixO = matrixA.Add(matrixB);
for (int i = 0; i < RowA; i ) {
for (int j = 0; j < ColA; j ) {
fprintf(fpOutput, "%lf ", matrixO.ele[i][j]);
printf("%lf", matrixO.ele[i][j]);
}
fprintf(fpOutput, "\n");
}
In the Matrix constructor section, I changed it like this.
public:
Matrix() {
numOfRow = 0;
numOfColumns = 0;
ele[4][4] = ele[0][0];
}
public:
Matrix() {
numOfRow = 0;
numOfColumns = 0;
ele[4][4] = {};
}
But both of these cases are wrong. How do we solve this issue?
CodePudding user response:
You are assigning a value to your matrix out-of-bounds:
ele[4][4] = 0;
The last element of double ele[4][4];
is ele[3][3];
This is undefined behavior, so it makes no sense to analyze what happens after it.
You can 0-initialize your Matrix
in its constructor like this:
Matrix(): ele(), numOfRow(), numOfColumns() {}