Reputation: 1
I have been trying to make this code for multidimensional matrices multiplication to work without much success for a couple of weeks by now.
The code works for any given multiplication between matrices of the same dimensions, however when I run something like 2x3*3x4 it only stores about half of the values in the resultant matrix, I have gone through many iterations of the programs including complete rewrites from scratch or working from a previous program that would do the same but without pointer notation and working. It is for an assignment, so I have the limitations of using the pointer notation and not using dynamic memory. I am not sure what I'am missing here even after going through documentation and examples. can you guys give me some suggestions of what is happing here?.
#include<stdio.h>
int main(){
int i, j, k, l, n1=1, n2=1, n3=1, n4=1, m1;
int p1[11][11], p2[11][11], p3[11][11];
printf("\n\nInput first matrix number of rows and columns : \n");
scanf("%d %d", &n1, &n2);
printf("\n\nInput second matrix number of rows and columns : \n");
scanf("%d %d", &n3, &n4);
printf("\n\nInput your values for the first matrix: \n");
for(i=0; i<n1; i++){
for(j=0; j<n2; j++){
printf("\n Input element of Row [%d] and Colunm[%d] = ", i+1, j+1);
scanf("%d", (*(p1+i)+j));
}
}
printf("\n\nInput your values for the second matrix : \n");
for(i=0; i<n3; i++){
for(j=0; j<n4; j++){
printf("\n Input element of Row [%d] and Colunm[%d] = ", i+1, j+1);
scanf("%d", (*(p2+i)+j));
}
}
printf("\n\n\n");
for(i=0;i<n1;i++){
for(j=0;j<n4;j++){
m1=0;
for(k=0;k<n3;k++){
m1+=(*(*(p1 + i) + k)) * (*(*(p2 + k) + j));
}
*(*(p3+j)+i)=m1;
printf("[%d][%d][%d][%d] ", *(*(p1+i)+j), *(*(p2+i)+j), *(*(p3+i)+j), m1);
}
}
printf("\n\n");
printf("\n\nThe result is: \n\n\n\t");
for(i=0; i<n1; i++){
printf("\n\t");
for(j=0; j<n4; j++){
printf("[%d]\t", *(*(p3+i)+j));
}
printf("\t\n\n\n\t");
}
printf("\n");
system("pause");
}
I don't get messages errors but for a given matrix multiplication of different dimensions 2x3*3x4 the result is:
12 12 0 0
12 12 9 2508544
or similar while the expected output is:
12 12 12 12
12 12 12 12
same applies for any matrices that have different dimensions, but square matrices come out alright.
Upvotes: 0
Views: 41
Reputation: 32727
In your calculation loop, you address *(*(p3 + j) + i)
, using the inner for loop variable first.
In your print loop, you use *(*(p3 + i) + j)
, using your outer for loop variable first.
So your print loop prints on the transpose of your result matrix.
Upvotes: 1