[英]Segmentation Fault in Matrix Inverse
我正在嘗試計算矩陣的逆,但我的代碼中出現分段錯誤錯誤,但我不確定發生這種情況的位置和原因。
這是我的代碼:
double** inverse(double *mat[], int n){
//identity matrix
double **I = malloc(sizeof(double*) * n);
for (int i=0; i<n; i++) I[i] = malloc(sizeof(double) * n);
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(i==j){
I[i][j] = 1;
}else{
I[i][j] = 0;
}
}
}
//works until here
double f = 0.0;
double sub = 0.0;
for(int p=0; p<n; n++){
f = mat[p][p];
for(int x=0; x<n; x++){
mat[p][x] = mat[p][x] / f;
I[p][x] = I[p][x] / f;
}
for(int i=p+1; i<n; i++){
f = mat[i][p];
for(int x=0; x<n; x++){
sub = mat[p][x] * f;
mat[i][x] = mat[i][x] - sub;
sub = I[p][x] * f;
I[i][x] = I[i][x] - sub;
}
}
}
for(int p=n-1; p>=0; p--){
for(int i=p-1; i>=0; i--){
f = mat[i][p];
for(int x=0; x<n; x++){
sub = mat[p][x] * f;
mat[i][x] = mat[i][x] - sub;
sub = I[p][x] * f;
I[i][x] = I[i][x] - sub;
}
}
}
//return I;
printf("I:\n");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
printf("%f ",I[i][j]);
}
printf("\n");
}
//free
for (int i=0; i<n; i++) free(I[i]);
free(I);
}
我傳入的矩陣是一個 nxn 矩陣,每行和每列都有值。 在我到達第一個 for 循環之前,代碼似乎一直在工作,我不知道為什么會出現此錯誤,因為循環停留在矩陣的邊界內。
您的錯誤似乎是這個 for 循環中的一個小錯字!
for(int p=0; p<n; n++)
您在每次迭代中增加n
,而不是p
因此您最終會訪問您不擁有的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.