Dynamically allocate memories to store a pair of matrices received from the user. Perform multiplication of these matrices. Use malloc() for dynamic allocation of memory and the function free() for deallocation.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int r = 3, c = 3, i, j, k;
int **arr = (int **)malloc(r * sizeof(int* ));
for (i=0; i<r; i++)
arr[i] = (int *)malloc(c * sizeof(int));
int **arr2=(int**)malloc(r*sizeof(int*));
for(i=0;i<r;i++)
arr2[i]=(int*)malloc(c*sizeof(int));
int **arr3=(int**)malloc(r*sizeof(int*));
for(i=0;i<r;i++)
arr3[i]=(int*)malloc(c*sizeof(int));
// Note that arr[i][j] is same as *(*(arr+i)+j)
printf("Enter elements of first array");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", (*(arr+i)+j));
printf("Enter elements of second array");
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
scanf("%d", (*(arr2+i)+j));
printf("first array\n");
for (i = 0; i < r; i++)
{for (j = 0; j < c; j++)
{printf("%d ", *(*(arr+i)+j));
}
printf("\n");
}
printf(" second array\n");
for (i = 0; i < r; i++)
{for (j = 0; j < c; j++)
{printf("%d ", *(*(arr2+i)+j));
}
printf("\n");
}
for (i = 0; i < r; i++)
for (j = 0; j < c; j++)
*(*(arr3+i)+j)=0;
for (i = 0; i < r; i++)
{for (j = 0; j < c; j++)
{
for(k=0;k<r;k++)
{
*(*(arr3+i)+j)=*(*(arr3+i)+j)+*(*(arr+i)+k)* *(*(arr2+k)+j);
}
}
}
printf(" multiplication\n");
for (i = 0; i < r; i++)
{for (j = 0; j < c; j++)
{printf("%d ", *(*(arr3+i)+j));
}
printf("\n");
}
return 0;
}
No comments:
Post a Comment