矩阵乘法程序

问题描述 投票:0回答:1

下面的代码显示了分段错误。 错误占优势 尝试了许多变化,但没有用

#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();
}

在turbo c ++上尝试过

错误139分段错误

c
1个回答
2
投票

错误139分段错误

这是因为

     for(j=0;i<=p-1;j++)

一定是

    for(j=0;j<=p-1;j++)

当前j增加没有结束所以c[i][j]=0;和其他访问是在数组之外具有未定义的行为(您的分段错误)


其他评论:

  • for(j=0; j < p; j++)是一个更好的选择兼容例如size_t与索引的正确类型
  • 我强烈建议您检查您的scanf是否成功,例如,目前您还不知道是否输入了有效数字 if (scanf("%d%d",&m,&n)!= 2) fprintf(stderr, "invalid numbers"); else {
  • 还要在必要时检查输入值> 0,这必须是行数和列数的情况
© www.soinside.com 2019 - 2024. All rights reserved.