提问者:小点点

如何在C++中消除分割错误?


我试图在C++中找到矩阵的行列式,当运行代码时,一个分段错误(核心转储)发生了,尽管我尝试更改代码很多次,但这个问题一直存在。 下面是代码:

#include <iostream>
using namespace std;

const int N = 4;


void get_cofs(int mat[N][N], int temp[N][N], int p, int q, int n){
    int i,j;
    for (int row=0; row<n; row++){
        for (int col=0; col<n; col++){
            if (row != p && col != q){
                temp[i][j++] = mat[row][col];

                if (j == n-1){
                    j = 0;
                    i++;
                }
            }
        }
    }
}


int compute_determinant(int mat[N][N], int n){
    int D =0;
    if (n == 1){
        return mat[0][0];
    }

    int temp[N][N] {0};
    

    int sign =1;
    for (int i = 0; i < n; i++)
    {
        get_cofs(mat,temp,0,i,n);
        D += sign * mat[0][i] * compute_determinant(temp, n-1);

        sign = -sign;
    }
    return D;
}


int main(){
    int mat[4][4] {{1, 0, 2, -1}, 
                     {3, 0, 0, 5}, 
                     {2, 1, 4, -3}, 
                     {1, 0, 5, 0} 
                    }; 
    cout<<compute_determinant(mat, N)<<endl;
    

    return 0;
}

共1个答案

匿名用户

就像@trebledj所说的,i和j是未初始化的。 使用未初始化的变量会导致未定义的行为。 看这个完整的治疗。

对于您的特定情况,将int i,j;更改为int i=0,j=0;,它将停止segfaulting。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|c++|中|消除|分割)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?