# matrix multiplication: code is only printing matrices but no multiplication product

Discussion in 'Meet and Greet' started by pako, Aug 21, 2012.

1. ### pakoNew Member

Joined:
Aug 21, 2012
Messages:
3
0
Trophy Points:
0
Code:
```#include<stdio.h>
#include<stdlib.h>

int mallocMatrix (int ***matrix, int A, int B) {
int i;
*matrix=(int**)malloc(sizeof(int*)*B);
for(i=0;i<B;i++)
(*matrix)[i]=(int*)malloc(sizeof(int)*A);
};

void getMatrix (int ***matrix, int A, int B) {
int i, j;
for(i=0;i<B;i++)
{
for(j=0;j<A;j++)
{
printf("Matrix[%d][%d]: ",i+1,j+1);
scanf("%d", &(*matrix)[i][j]);
}
}
};

void putMatrix (int ***matrix, int A, int B) {
int i, j;
printf ("\n");
for(i=0;i<B;i++)
{
for(j=0;j<A;j++)
{
printf ("%d ", (*matrix)[i][j]);
}
printf ("\n");
}
};

int main(){
int **matrix;
int **matrix_2;
int **matrix_3;
int n, m, p, d, temp;

printf ("[1st matrix] number of columns:");
scanf ("%d", &n);
printf ("[1st matrix] number of rows:");
scanf ("%d", &m);

mallocMatrix (&matrix, n, m);
getMatrix (&matrix, n, m);

printf ("[2nd matrix] number of columns:");
scanf ("%d", &p);
printf ("[2nd matrix] number of rows:");
scanf ("%d", &d);

if (n==d)
{
mallocMatrix (&matrix_2, p, d);
getMatrix (&matrix_2, p, d);
}
else
{
printf ("Number of columns in 1st matrix must equal number of rows in the 2nd matrix");
return -1;
}

putMatrix (&matrix, n, m);
putMatrix (&matrix_2, p, d);

mallocMatrix (&matrix_3, m, p);

/* matrix multiplication */

int i, j, k;
for(i = 0; i < m; i++)
{
for(j = 0; j < p; j++)
{
for(k = 0; k < m; k++)
{
matrix_3[i][j] = (matrix_3[i][j] + (matrix[i][k] * matrix_2[k][j]));
}
}
} /* end matrix multiplication */

putMatrix (&matrix_3, m, p);
}```