我正在嘗試計算矩陣的逆,但我的代碼中出現分段錯誤錯誤,但我不確定發生這種情況的位置和原因。
這是我的代碼:
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 回圈之前,代碼似乎一直在作業,我不知道為什么會出現此錯誤,因為回圈停留在矩陣的邊界內。
uj5u.com熱心網友回復:
您的錯誤似乎是這個 for 回圈中的一個小錯字!
for(int p=0; p<n; n )
您n在每次迭代中都在遞增,而不是p這樣您最終會訪問您不擁有的記憶體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336468.html
上一篇:為什么strlen()算錯了?
下一篇:不改變值的引數數量的資料驗證
