所以我想弄清楚如何使用指针将 2 个矩阵相乘。它以现在的方式成功地工作,但是我不想使用传统的数组访问方法,而是想学习指针的使用。
这是我的代码:
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
#include <iostream>
/* Routines called. */
int loadMatrixFromFile(char *filename, int *data);
void showMatrix(int *data, int len);
int makeIdent(int matrixB[5][5], int length);
int matrixA[5][5];
int matrixB[5][5];
int matrixC[5][5];
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]);
int main(){
int len, data[1000];
len = loadMatrixFromFile("Numbers.txt", data);
showMatrix(data, len);
makeIdent(matrixB,len);
multiplyMatrices(matrixA, matrixB, matrixC);
}
int makeIdent(int matrixB[5][5], int len){
int i,j;
printf("Matrix B is: \n");
for(i=0;i<5;i++){
for(j=0;j<5;j++){
if(i==j){
matrixB[i][j]=1;
printf("%d ",matrixB[i][j]);
}
else{
matrixB[i][j]=0;
printf("%d ",matrixB[i][j]);
}
}
printf("\n");
}
return matrixB[i][j];
printf("\n");
}
int loadMatrixFromFile(char *filename, int *data){
FILE *in;
int len;
int j;
in = fopen(filename, "r");
if (in == NULL) {
printf("Could not find file: %s \n", filename);
}
else {
printf("Reading numbers...\n");
fscanf(in, "%d", &len);
printf("reading %d numbers from file %s ....\n", len, filename);
for(j=0;j<len;j++) {
fscanf(in, "%d", data + j);
}
fclose(in);
}
for(int i = 0; i<5; i++){
for(int j = 0; j < 5; j++){
matrixA[i][j] = *(data + i*5 + j);
}
}
return len;
}
void showMatrix(int *data, int len){
int j;
int count = 0;
printf("Showing %d numbers from data array....\n", len);
printf("Matrix A is: \n");
for(j=0;j<len;j++) {
printf("%d ", *(data + j));
count++;
if(count % 5 == 0){
printf("\n");
}
}
printf("\n");
}
void multiplyMatrices(int matrixA[5][5], int matrixB[5][5],int matrixC[5][5]){
int i, n, j;
int count = 0;
printf("\n");
printf("Matrix A x Matrix B is: \n");
for (i = 0; i<5; i++){
for (j = 0; j<5; j++){
matrixC[i][j] = 0;
matrixC[i][j] += matrixA[i][j]*matrixB[i][j];
printf("%d ",matrixC[i][j]);
count++;
if(count % 5 == 0){
printf("\n");
}
}
}
}