I am trying to learn 2d arrays. I have stumbled upon a problem. It says to read two matrices of order a*b and m*n using a function named readMatrix(), multiply the matrices using processMatric() and show the result using showMatrix().
I am trying to solve it using only arrays.
Here's what I tried to do.
#include <stdio.h>
#include<math.h>
void readMatrix();
void processMatrix(int p[][100],int q[][100],int a,int b,int m,int n);
void showMatrix(int c[][100],int a,int n);
int main() {
readMatrix();
}
void readMatrix()
{
int i,j,m,n,a,b;
printf("For matrix 1 \n");
printf("Enter the number of rows: ");
scanf("%d",&a);
printf("Enter the number of columns: ");
scanf("%d",&b);
printf("For matrix 2 \n");
printf("Enter the number of rows: ");
scanf("%d",&m);
printf("Enter the number of columns: ");
scanf("%d",&n);
int p[a][b];
int q[m][n];
if (b == m)
{
printf("For 1st Matrix\n");
for(i = 0;i<a;i++)
{
for(j = 0; j < b;j++)
{
printf("%d row %d column: ",i+1,j+1);
scanf("%d",&p[i][j]);
}
}
printf("For 2nd Matrix\n");
for(i = 0;i < m;i++)
{
for(j = 0; j < n;j++)
{
printf("%d row %d column: ",i+1,j+1);
scanf("%d",&q[i][j]);
}
}
}
else
{
printf("Enter a valid dimension. ");
}
processMatrix(p,q,a,b,m,n);
}
void processMatrix(int p[][100],int q[][100],int a,int b,int m,int n)
{
int i,j,k;
int c[a][n];
for(i=0;i < a;i++)
{
for(j = 0; j < n;j++)
{
c[i][j]=0;
for(k = 0; k < b;k++)
{
c[i] [j] = c[i][j] + p[i][k] * q[k][j];
}
}
}
showMatrix(c,a,n);
}
void showMatrix(int c[][100],int a,int n)
{
int i,j;
for(i = 0; i < a; i++)
{
for(j = 0; j< n; j++)
printf("%d ",c[i][j]);
}
printf("\n");
}
This program does read the elements but displays grabage value. Where am I going wrong?
You define the arrays with dimensions of
abybandmbyn:but you pass them to routines expecting something by 100:
That cannot work unless
bandnare 100. Defining a matrix asp[a][b]says there arearows each of which containsbint. If row 0 starts at location x in memory, then row 1 startsbelements beyond x. But, whenprocessMatrixreceives location x, it expects row 1 to start 100 elements beyond x. So it reads data from the wrong location in memory.Since your C compiler appears to support variable length arrays, simply declare your routines to use the proper dimensions:
Note the first dimension in each case,
ainpandminq, is not necessary for the compiler, as it does not need to know how big the array is, just how its elements are laid out. However, including it may help make the intent of the program clear.(I did not check your code for additional problems beyond this one.)