In: Computer Science
Develop a C program for matrix multiplication focusing on using malloc and pointers WITHOUT USING BRACKETS [] !!
* DO not use [ ] 'brackets', focus on using malloc, calloc, etc...
Program will ask user for the name of the text file to be
read
Read the datafile with format:
1
2
1
1 2
3
4
So the first three lines will represent m, n, p (Matrix A: m x n
||| Matrix B: n x p), follwing are the two matrices.
Representing:
A = |1 2| B = |3|
|4|
------------------------------------------------
example input and output:
Matrix A contents:
1 2
3 4
5 6
Matrix B contents:
7 8
9 10
11 12 13 14
Matrix A * B is:
29 32 35 38
65 72 79 86
101 112 123 134
The datafile read for this example is:
3
2
4
1 2
3 4
5 6
7 8 9 10
11 12 13 14
If you have any doubts, please give me comment...
#include<stdio.h>
#include<stdlib.h>
int main(){
char filename[50];
int m, n, p, i, j, k;
int **A, **B, **mult;
printf("Enter filename: ");
scanf("%s", filename);
FILE *fp;
fp = fopen(filename, "r");
if(fp==NULL){
printf("Unable to open file\n");
return 0;
}
fscanf(fp, "%d %d %d", &m, &n, &p);
A = (int **)malloc(m*sizeof(int *));
for(i=0; i<m; i++){
*(A+i) = (int *)malloc(n*sizeof(int));
for(j=0; j<n; j++){
fscanf(fp, "%d", (*(A+i)+j));
}
}
B = (int **)malloc(n*sizeof(int *));
for(i=0; i<n; i++){
*(B+i) = (int *)malloc(p*sizeof(int));
for(j=0; j<p; j++)
fscanf(fp, "%d", (*(B+i)+j));
}
mult = (int **)malloc(m*sizeof(int *));
for(i=0; i<m; i++)
*(mult+i) = (int *)malloc(p*sizeof(int));
printf("Matrix A contents:\n");
for(i=0; i<m; i++){
for(j=0; j<n; j++){
printf("%4d", *(*(A+i)+j));
}
printf("\n");
}
printf("Matrix B contents:\n");
for(i=0; i<n; i++){
for(j=0; j<p; j++){
printf("%4d", *(*(B+i)+j));
}
printf("\n");
}
for(i=0; i<m; i++){
for(j=0; j<p; j++){
*(*(mult+i)+j) = 0;
for(int k=0; k<n; k++){
*(*(mult+i)+j) += *(*(A+i)+k) * *(*(B+k)+j);
}
}
}
printf("Matrix A * B is:\n");
for(i=0; i<m; i++){
for(j=0; j<p; j++){
printf("%4d", *(*(mult+i)+j));
}
printf("\n");
}
for(i=0; i<m; i++){
free(*(A+i));
free(*(mult+i));
}
for(i=0; i<n; i++)
free(*(B+i));
free(A);
free(B);
free(mult);
return 0;
}