I want to create a function for matrix multiplication in C. To this end I defined the function matrix_mult().
When I call this function with the following parameters:
int matrix1[l][m] = {{1,2}, {1,2}};
int matrix2[m][k] = {{1,0}, {0,1}};
in the main() method like so:
int main()
{
int matrix1[l][m] = {{1,2}, {1,2}};
int matrix2[m][k] = {{1,0}, {0,1}};
matrix_mult(matrix1, matrix2);
return 0;
}
I get the following result:
59 59
68 60
The correct result would be:
1 2
1 2
I just don't get what the code is doing wrong.
The definition of the function matrix_mult() is given below:
#define l 2
#define m 2
#define k 2
int matrix_mult(int m1[l][m], int m2[m][k]) {
int res[l][k];
for(int row=0;row<l;row++){
for (int col=0;col<k;col++){
for(int j=0;j<m;j++){
res[row][col] += m1[row][j]*m2[j][col];
}
}
}
printf("Result of matrix multiplication is:\n");
for(int i=0;i<l;i++) {
for(int j=0;j<k;j++){
printf("%d ", res[i][j]);
}
printf("\n");
}
return 0;
}
Does anybody of you guys know what's up here?
Initialize the res
array to 0.
int res[l][k] = {{0}};