C程序指针实现矩阵乘法
时间: 2024-03-22 15:41:58 浏览: 17
以下是一个简单的C语言程序,使用指针实现矩阵乘法:
```c
#include <stdio.h>
int main() {
int m, n, p, q, i, j, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("Enter the number of rows and columns of first matrix: ");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
scanf("%d", *(first + i) + j);
}
}
printf("Enter the number of rows and columns of second matrix: ");
scanf("%d%d", &p, &q);
if (n != p) {
printf("Matrices can't be multiplied.\n");
} else {
printf("Enter the elements of second matrix:\n");
for (i = 0; i < p; i++) {
for (j = 0; j < q; j++) {
scanf("%d", *(second + i) + j);
}
}
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
for (k = 0; k < p; k++) {
sum += *(*(first + i) + k) * *(*(second + k) + j);
}
*(*(multiply + i) + j) = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");
for (i = 0; i < m; i++) {
for (j = 0; j < q; j++) {
printf("%d ", *(*(multiply + i) + j));
}
printf("\n");
}
}
return 0;
}
```
该程序使用三个二维数组 `first`、`second` 和 `multiply`,分别存储输入的两个矩阵和它们的乘积。程序先提示用户输入第一个矩阵的行数和列数,然后读取矩阵元素,存储到 `first` 数组中。然后提示用户输入第二个矩阵的行数和列数,读取矩阵元素,存储到 `second` 数组中。如果两个矩阵不能相乘,则输出一条错误信息。如果两个矩阵可以相乘,则计算它们的乘积,并将结果存储到 `multiply` 数组中。最后,程序输出乘积矩阵的元素。