我编写了这个程序来计算使用Cramer规则的3X3线性方程组的解。程序工作并输出正确的结果但在正常结束之前会提示错误消息"运行时检查失败#2 - 变量x2周围的堆栈已损坏"并且程序没有正确终止。这是代码:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void cramer (double** a, double* b);
int main()
{
int i,j;
double** a;
double* b;
a=(double**)malloc(3*sizeof(double*));
for (i=0;i<3;i++)
a[i]=(double*)malloc(3*sizeof(double));
b=(double*)malloc(3*sizeof(double));
printf ("This program computes the solutions of a system of linear equations 3X3\n");
printf ("a11x1+a12x2a13x3=b1\n");
printf ("a21x2+a22x2+a23x3=b2\n");
printf ("a31x3+a32x2+a33x3=b3\n");
printf ("Insert a and b\n");
for (i=0;i<3;i++){
for (j=0;j<3;j++){
printf("a%d%d\n",i+1,j+1);
scanf("%lf",&a[i][j]);
}
printf("b%d\n",i+1);
scanf("%lf",&b[i]);
}
cramer(a,b);
for (i=0;i<3;i++)
free(a[i]);
free(a);
free(b);
return 0;
}
void cramer(double** a,double* b)
{
int i,j;
double x1[3][3],x2[3][3],x3[3][3],A[3][3];
for (i=0;i<3;i++){
for (j=0;j<3;j++){
A[i][j]=a[j][i];
x1[i][j]=a[i][j]*A[i][j];
x2[i][j]=a[i][j]*A[i][j];
x3[i][j]=a[i][j]*A[i][j];
}
x1[i][1]=b[i];
x2[i][2]=b[i];
x3[i][3]=b[i];
}
printf(" %f %f %f\n",x1[0][0],x1[0][1],x1[0][2]);
printf("x1=%f %f %f\n",x1[1][0],x1[1][1],x1[1][2]);
printf(" %f %f %f\n",x1[2][0],x1[2][1],x1[2][2]);
printf("\n");
printf(" %f %f %f\n",x2[0][0],x2[0][1],x2[0][2]);
printf("x2=%f %f %f\n",x2[1][0],x2[1][1],x2[1][2]);
printf(" %f %f %f\n",x2[2][0],x2[2][1],x2[2][2]);
printf("\n");
printf(" %f %f %f\n",x3[0][0],x3[0][1],x3[0][2]);
printf("x3=%f %f %f\n",x3[1][0],x3[1][1],x3[1][2]);
printf(" %f %f %f\n",x3[2][0],x3[2][1],x3[2][2]);
}
答案 0 :(得分:0)
x1[i][1]=b[i];
x2[i][2]=b[i];
x3[i][3]=b[i]; // index is out of range
可能这就是你的意思:
x1[i][0]=b[i];
x2[i][1]=b[i];
x3[i][2]=b[i];
答案 1 :(得分:0)
该行
x3[i][3]=b[i];
正在访问超出您定义的数组范围的内存。 C具有从零开始的索引,因此对于3x3阵列,最大有效索引为2。
可能应该
x1[i][0]=b[i];
x2[i][1]=b[i];
x3[i][2]=b[i];