My code below works just fine. However, I want to know how I can store the matrices in heap memory. The code accepts 3 positive integers a, b and c from the user. User then input two matrices. First matrix is n(rows) by m(columns) and second matrix is m(rows) by p(columns).
the matrix product/output is n rows by p columns,e.g; Sample Input
4
3
2
14 9 3
2 11 15
0 12 17
5 2 3
12 25 9 10
8 5
Sample Output
273 455
243 235
244 205
102 160
int main(void) {
int row1, row2, col1, col2, i, j, e;
int temp, **matrix1, **matrix2, **mtxProduct;
scanf("%d", &row1);
scanf("%d", &col1);
temp = col1;
row2=temp;
scanf("%d", &col2);
if (col1 != row2) {
printf("\nIncorrect combination!\n");
return 1;
}
matrix1 = (int**) malloc(row1 * sizeof(int*));
//read elements of 1st matrix
for (i = 0; i < row1; i++) {
matrix1[i] = (int*) malloc(col1 * sizeof (int));
for (j = 0; j < col1; j++) {
scanf("%d %d %d\n", &matrix1[i][j], &matrix1[i][j], &matrix1[i][j]);
}
}
matrix2 = (int**) malloc(row2 * sizeof (int*));
//read elements of 2nd matrix
for (i = 0; i < row2; i++) {
matrix2[i] = (int*) malloc(col2 * sizeof (int));
for (j = 0; j < col2; j++) {
scanf("%d %d %d", &matrix2[i][j], &matrix2[i][j], &matrix2[i][j]);
}
}
mtxProduct = (int**) malloc(row1 * sizeof (int*));
for (i = 0; i < col2; i++) {
mtxProduct[i] = (int*) malloc(col2 * sizeof (int));
}
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
mtxProduct[i][j] = 0;
for (e = 0; e < row2; e++) {
mtxProduct[i][j] +=(matrix1[i][e] * matrix2[e][j]);
}
}
}
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
printf("%d ", mtxProduct[i][j]);
}
}
return 0;
}