我下面的代码工作得很好。但是,我想知道如何将矩阵存储在堆内存中。该代码接受来自用户的 3 个正整数 a、b 和 c。然后用户输入两个矩阵。第一个矩阵是 n(rows) x m(columns),第二个矩阵是 m(rows) x p(columns)。
矩阵乘积/输出是 n 行乘 p 列,例如; 样本输入
4
3
2
14 9 3
2 11 15
0 12 17
5 2 3
12 25 9 10
8 5
样本输出
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;
}