2011-03-08 24 views
0

在此程序运行期间,出现分段错误。我试图解决一个线性方程,从一个.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; 
} 

回答

2

它看起来像矩阵A未分配。我认为你需要这个分配a后:

A[k-1] = a; 
+0

in prob2()or guass()?谢谢 – 2011-03-08 01:05:26

+0

@Dave:在prob2()函数中。在4行中读取的循环为'a'分配一个数组,但是在填充它之后不会做任何事情(据我所知)。 – 2011-03-08 01:07:18

+0

@Dave在您发布的代码中只有一个'k'的用法,它不是'gauss'。 – 2011-03-08 01:13:33

0

当算法对角线上遇到0这通常发生。您需要使用pivoting来避免这种情况。有关详细信息,请参阅有关高斯消除的Wikipedia article

+0

这不会产生segvio。 – 2011-03-08 01:06:43

0

你永远不会在A中存储任何东西。你在你的k = 1 ... 4循环中malloc,但是你永远不会保存你的malloc。