编写一个函数multi,实现大小两个矩阵相乘,通过主函数调用该函数,并输出结果,要求使用函数、指针
时间: 2023-07-15 17:12:54 浏览: 75
两个矩阵相乘的实现程序
5星 · 资源好评率100%
下面是使用函数、指针实现两个矩阵相乘的程序:
```c
#include <stdio.h>
#include <stdlib.h>
void multi(int **matrix1, int **matrix2, int **result, int row1, int col1, int col2)
{
int i, j, k;
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
result[i][j] = 0;
for (k = 0; k < col1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
}
int main()
{
int i, j;
int row1 = 2, col1 = 3, row2 = 3, col2 = 2;
int **matrix1, **matrix2, **result;
//allocate memory for matrix1
matrix1 = (int **)malloc(row1 * sizeof(int *));
for (i = 0; i < row1; i++) {
matrix1[i] = (int *)malloc(col1 * sizeof(int));
}
//allocate memory for matrix2
matrix2 = (int **)malloc(row2 * sizeof(int *));
for (i = 0; i < row2; i++) {
matrix2[i] = (int *)malloc(col2 * sizeof(int));
}
//allocate memory for result
result = (int **)malloc(row1 * sizeof(int *));
for (i = 0; i < row1; i++) {
result[i] = (int *)malloc(col2 * sizeof(int));
}
//initialize matrix1
printf("Enter elements for matrix1:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
scanf("%d", &matrix1[i][j]);
}
}
//initialize matrix2
printf("Enter elements for matrix2:\n");
for (i = 0; i < row2; i++) {
for (j = 0; j < col2; j++) {
scanf("%d", &matrix2[i][j]);
}
}
//multiply matrix1 and matrix2
multi(matrix1, matrix2, result, row1, col1, col2);
//print the result matrix
printf("The result is:\n");
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
//free memory
for (i = 0; i < row1; i++) {
free(matrix1[i]);
}
free(matrix1);
for (i = 0; i < row2; i++) {
free(matrix2[i]);
}
free(matrix2);
for (i = 0; i < row1; i++) {
free(result[i]);
}
free(result);
return 0;
}
```
函数multi接收三个矩阵和矩阵的行列数,通过指针实现矩阵相乘操作。在主函数中,先动态分配内存空间并初始化两个矩阵,然后调用multi函数进行相乘操作,最后输出结果并释放内存。
阅读全文