c - 高斯消除期间段错误(核心转储)

标签 c matrix segmentation-fault

在该程序运行期间,我遇到段错误。我正在尝试使用从 .dat 文件接收的数字来求解线性方程。我可以在高斯函数之前到达该部分,但它会在之后转储。有什么帮助吗?谢谢。

    void prob2(void)
{
        FILE *matrix;

        matrix=fopen("matrix.dat", "r");
        double a1, a2, a3, a4, **A, *a, *rhs, length;
        int k, row;
        A=(double **)malloc(4*sizeof(double *));
        printf("\n");
        for(k=1;k<=4; k++) 
        {
                a=(double *)malloc(4*sizeof(double));
                fscanf(matrix, "%lf %lf %lf %lf", &a1, &a2, &a3, &a4);
                a[0]=a1;
                a[1]=a2;
                a[2]=a3;
                a[3]=a4;
                printf(" a[%d][] = %5.2f %5.2f %5.2f %5.2f\n", k, a[0], a[1], a[2], a[3]);
        }
        rhs=(double *)malloc(4*sizeof(double));
        fscanf(matrix, "%lf %lf %lf %lf", &a1, &a2, &a3, &a4);
        rhs[0]=a1;
        rhs[1]=a2;
        rhs[2]=a3;
        rhs[3]=a4;
        printf("\nb[]={  %.3f,   %.3f,  %.3f,   %.3f  }\n", rhs[0],rhs[1],rhs[2],rhs[3]);
        printf("hiii");
        gauss(4, A, rhs);
        /* print the solution x[] stored in rhs[]:*/
        printf("x[]={%7.3f, %7.3f, %7.3f, %7.3f  }\n", 
        rhs[0], rhs[1], rhs[2], rhs[3]);
        length=sqrt(pow(rhs[0],2)+pow(rhs[1],2)+pow(rhs[2],2)+pow(rhs[3],2));
        printf("The length of x[] is  %.6lf", length);
        /* free memory */
        for(row=0; row<4; row++) free(A[row]);
        free(A); 
        free(rhs);
        fclose(matrix);

}

void gauss(int n, double **A, double *rhs)
{
/* By Gauss elimination, solve a system of equations:
   A[][]*x[] = rhs[] where A[][] (n x n)
   and rhs[] (n x 1) are input */

/* x[] is stored in rhs[] */
printf("hiii");
double one = 1.0, zero=0.0;
double b, c, d;
int nm, row, col, krow;
nm = n - 1;
if(n == 1)
{
rhs[0] /= A[0][0]; A[0][0] = one;
return;
}
/* forward reduction */
for(row=0; row<nm; row++)
{
b = A[row][row]; A[row][row] = one;
for(col=row+1; col<n; col++) A[row][col] /= b;
rhs[row] /= b;
/* sweep rows of A[row+1][] to A[nm][] */
for(krow=row+1; krow<n; krow++)
{
c = A[krow][row]; A[krow][row] = zero;
for(col=row+1; col<n; col++) A[krow][col] -= c * A[row][col];
rhs[krow] -= c * rhs[row];
}
}
/* back substitution */

rhs[nm] /=A[nm][nm];
for(row=nm-1; row>=0; row--)
{
for(col=row+1; col<n; col++) rhs[row] -= A[row][col]*rhs[col];
}
return;
}

最佳答案

看起来矩阵A没有被赋值。我认为您在分配 a 后需要这个:

A[k-1] = a;

关于c - 高斯消除期间段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5227130/

相关文章:

c - linux和windows关于颜色的问题

我可以写入非常量结构的 const 成员吗?

c - 为什么不接受()阻止?

c - 链表-插入新节点

matlab - Drazin 逆矩阵

python - 将矩阵保存为图像,恢复后不做任何更改

php - 通过 PHP 启动 C 程序时出现段错误

c++ - NxN 行列式函数 (C++) 的代码问题

ios - 命令因信号 : Segmentation Fault 11 -- Xcode 8 Swift 3 而失败

c - 没有定义未使用数组的段错误