Wednesday 15 January 2014

matrix - how to build function that multiply matrices created via struct in C -



matrix - how to build function that multiply matrices created via struct in C -

i supposed build matrix_mul function display result of multiplication between 2 matrices created via struct. problem is, function not multiply value within matrices instead homecoming interger.

#include<stdio.h> #include<stdlib.h> typedef struct{ int rows; int cols; int **data; } matrix; matrix matrix_mul(int **a, int **b){ int rowa=(sizeof(a)/sizeof(a[0])); int cola=(sizeof(a)/sizeof(a[0][0]))/rowa; int rowb=(sizeof(b)/sizeof(b[0])); int colb=(sizeof(b)/sizeof(b[0][0]))/rowb; int i, j, **mulmatrix; if(cola != rowb) printf("error: cannot multiply matrices"); else{ int i, j, k; mulmatrix = (int **)malloc(rowa * sizeof(int *)); for(i=0; i<rowa; i++) mulmatrix[i] = (int *)malloc(colb * sizeof(int)); for(i=0; i<rowa; ++i){ for(j=0; j<colb; ++j){ for(k=0; k<cola; ++k) { mulmatrix[i][j]+= a[i][k] * b[k][j]; } } } } printf("matrix: \n\n"); for(i=0; i< rowa; i++){ for(j=0; j< colb; j++){ printf("%d ", mulmatrix[i][j]); } printf("\n\n"); } } int main() { int i, j; matrix a, b; printf("matrix1 - come in number of rows , cols: "); scanf("%d %d", &a.rows, &a.cols); a.data = (int **)malloc(a.rows * sizeof(int *)); printf("enter matrix values: "); for(i=0; i<a.rows; i++){ a.data[i] = (int *)malloc(a.cols * sizeof(int)); for(j=0; j<a.cols; j++){ scanf("%d", &a.data[i][j]); } } printf("matrix2 - come in number of rows , cols: "); scanf("%d %d", &b.rows, &b.cols); b.data = (int **)malloc(b.rows * sizeof(int *)); printf("enter matrix values: "); for(i=0; i<b.rows; i++){ b.data[i] = (int *)malloc(b.cols * sizeof(int)); for(j=0; j<b.cols; j++){ scanf("%d", &b.data[i][j]); } } matrix_mul(a.data, b.data); homecoming 0; }

these lines

int rowa=(sizeof(a)/sizeof(a[0])); int cola=(sizeof(a)/sizeof(a[0][0]))/rowa;

won't give results looking for.

sizeof(a) sizeof(int**) , sizeof(a[0]) sizeof(int*). since pointers of same size, rowa set 1. cola set sizeof(int**)/sizeof(int), constant value. 1 time again, it's not value hoping get.

you should pass matrix objects, a , b matrix_mul. that'll give size of matrices utilize multiplying them.

matrix matrix_mul(matrix a, matrix b){

of course, need modify implementation accordingly.

c matrix

No comments:

Post a Comment