c++ - 如何摆脱 C++ 中的段错误错误?

标签 c++ matrix segmentation-fault

我试图在 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;
}

最佳答案

就像@TrebledJ 所说, i 和 j 未初始化。使用未初始化的变量会导致未定义的行为。见 this进行全面治疗。
对于您的具体情况,更改 int i,j;int i=0,j=0;它将停止段错误。

关于c++ - 如何摆脱 C++ 中的段错误错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62729979/

相关文章:

c - 返回整数指针或数组基地址时出现段错误

c++ - 从无符号整数类型样式转换。这种风格好吗?

arrays - Matlab OOP 从对象数组访问属性

python - scipy.linalg.inv 是否检查矩阵是否为对角矩阵?

c - 前序树遍历有效但后序无效

c - 如何制作 int val[100000000] 数组?

c++ - 带有 boolean 值的 ASSERT_EQ 在 gtest 中失败

c++ - 我应该为 DirectX 11 使用什么 SDK?

C++ <算法> 实现解释

python - block 三对角矩阵python