Reputation: 15
The code below shows segmentation error.
The error prevails
Tried many changes but of no use
#include<conio.h>
#include<stdio.h>
void main()
{
static int a[100][100],b[100][100],c[100][100]={0};
int m,n,p,i,j,k;
printf("Enter no pf rows and colums for matrix A");
scanf("%d%d",&m,&n);
for(i=0;i<=m-1;i++)
{
for(j=0;j<=n-1;j++)
{
printf("enter no.");
scanf("%d",&a[i][j]);
}
}
printf("Enter no. of column for matrix b");
scanf("%d",&p);
for(i=0;i<=n-1;i++)
{
for(j=0;j<=p-1;j++)
{
printf("enter no.");
scanf("%d",&b[i][j]);
}
}
for(i=0;i<=m-1;i++)
{
for(j=0;i<=p-1;j++)
{
c[i][j]=0;
for(k=0;k<=n-1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf(" The resultant matrix is");
for(i=0;i<=m-1;i++)
{
for(j=0;j<=p-1;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
getch();
}
Tried it on turbo c++
Error 139 Segmentation error
Upvotes: 0
Views: 50
Reputation: 32586
Error 139 Segmentation error
this is because
for(j=0;i<=p-1;j++)
must be
for(j=0;j<=p-1;j++)
currently j is increased without end so c[i][j]=0;
and other accesses are out of the array with an undefined behavior (your segmentation fault)
Other remarks :
to do for(j=0; j < p; j++)
is a better choice compatible with for instance size_t
with is the right type for an index
I strongly encourage you to check if your scanf success, currently you do not know if valid numbers was enter, for instance
if (scanf("%d%d",&m,&n)!= 2)
fprintf(stderr, "invalid numbers");
else {
also check when necessary the enter values are > 0, this must be the case for the number of rows and columns
Upvotes: 2