1

2つのファイルの値がそれぞれ2^14であるにもかかわらず、このコードでセグメンテーション違反が発生しています。誰かがその理由を教えてもらえますか?

#define N 128
#include<stdio.h>
#include <malloc.h>
int A[N][N];
int B[N][N];
int C[N][N];
void mmul();

int main()
{
    int p,q;
    FILE *fp;
    fp=fopen("A.txt","r");
    if(fp=NULL)
        printf("Error\n");
    printf("A");
    for(p=0;p<(1<<7);p++)
    {
        for(q=0;q<(1<<7);q++)
        {
            fscanf(fp, "%d", &A[p][q]);
        }
    }
    fclose(fp);
    fp=fopen("B.txt","r");
    if(fp=NULL)
        printf("Error\n");
    for(p=0;p<(1<<7);p++)
    {
        for(q=0;q<(1<<7);q++)
        {
            fscanf(fp, "%d", &B[p][q]);
        }
    }
    fclose(fp);
    printf("here");
    mmul();
}

void mmul()
{
    int i,j,k;
    unsigned int sum;
    for(i=0;i<N;i++)
    {
        for(j=0;j<N;j++)
        {
            sum=0;
            for(k=0;k<N;k++)
            {
                sum=sum+(A[i][k]*B[k][j]);
            }
            C[i][j]=sum;
        }
    }
}
4

2 に答える 2

8

警告付きでコンパイル

if (fp = NULL)
于 2012-11-09T16:30:44.583 に答える
5
if(fp=NULL)
printf("Error\n");`
  • 全身ifです。したがって、ファイルがない場合は、NULLを取得し、fp「エラー」を出力して、NULLで実行を続行しますfp。セグメンテーション違反が発生します。

また、これは割り当てであり、比較ではないため、エラーを出力するのではなく、常にNULLfpを取得します。

exitステートメントを追加する必要があります。

if (fp == NULL) {
   fprintf(stderr, "Error: failed to open file\n");
   return -1;
}
于 2012-11-09T16:28:45.853 に答える