Develop a C program for matrix multiplication focusing on using malloc and point
ID: 3564452 • Letter: D
Question
Develop a C program for matrix multiplication focusing on using malloc and pointers
* 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
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char* s=malloc(200*(sizeof(char)));
scanf("%s",s);
printf("%s ",s );
FILE* file = fopen (s, "r");
int i,k=0,sum,j;
int m,n,p;
fscanf (file, "%d", &k);
m=k;
fscanf (file, "%d", &k);
n=k;
fscanf (file, "%d", &k);
p=k;
int** a;
a = malloc(m* sizeof(int *));
for (i = 0; i <m; i++)
a[i] = malloc(n * sizeof(int));
int **b;
b = malloc(n * sizeof(int *));
for (i = 0; i < n; i++)
b[i] = malloc(p*sizeof(int));
int **c;
c = malloc(m* sizeof(int *));
for (i = 0; i < m; i++)
c[i] = malloc(p * sizeof(int));
for(i=0;i<m;i++){
for(j=0;j<n;j++){
fscanf (file, "%d", &k);
a[i][j]=k;
}
}
for(i=0;i<n;i++){
for(j=0;j<p;j++){
fscanf (file, "%d", &k);
b[i][j]=k;
}
}
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
for ( k= 0 ; k < p ; k++ )
{
sum = sum + a[i][k]*b[k][j];
}
c[i][j] = sum;
sum = 0;
}
}
for(i=0;i<m;i++){
for(j=0;j<p;j++)
printf("%d",c[i][j]);
printf(" ");
}
fclose (file);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.