当输入是阶数大于2的矩阵时,为什么会出现细分错误?

时间:2019-06-07 07:01:37

标签: c arrays

问题是要找到C语言中NXN矩阵的行列式。我写了下面的代码。我正在获取n = 2矩阵的输出。但是对于n> 2,程序会说“分段错误(内核已转储)”。请帮我。我尝试编写尽可能正确的代码。语法错误的任何突出显示将不胜感激。提前致谢。 (我正在使用Ubuntu 18.04 LTS Terminal。)

Input - 2 (Order of Matrix)
        1 (Enter the Elements)
        2
        3
        4
Output -1 2 (Entered Matrix)
        3 4  
       -2 (Value of Determinant)
Input - 3 (Order of Matrix)
        1 (Enter the Elements)
        2
        3
        4
        5
        6 
        7
        8
        9
Output -1 2 3 (Entered Matrix)
        4 5 6
        7 8 9 
        Segementation Fault(Core Dumped)

#include <stdio.h>
int determinent(int n,int p[n][n]);
int main()
{
int n,i,j;
printf("Enter the order of the matrix:\n");
scanf("%d",&n);
int a[n][n];
printf("Enter the elements of the NXN matrix.\n");
for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        scanf("%d",&a[i][j]);
    }
}
printf("The entered matrix is:\n");
for(i=0;i<n;i++)
{
    for(j=0;j<n;j++)
    {
        printf("%d ",a[i][j]);
    }
    printf("\n");
}
printf("\n");
printf("The determinent of the matrix is %d\n",determinent(n,a));
return 0;
}

int determinent(int n,int p[n][n])
{
int det,k,m,s=1,i,j,l=0;
if(n==2)
{
    det = p[0][0]*p[1][1] - p[0][1]*p[1][0];
}
else
{
    for(k=0;k<n;k++,s=-s,l++)
    {
        if(l==0)
        {
            det = 0;
        }

        int b[n-1][n-1];
        m = (p[0][k])*(s);
        for(i=0;i<n-1;i++)
        {
            for(j=0;j<n-1;j++)
            {
                if(k==0)
                {
                    b[i][j] = p[i+1][j+1];
                }
                else
                {
                    int c;
                    for(c=0;c<k;c++)
                    {   
                        b[i][j] = p[i+1][j+1];
                    }
                    for(c=k+1;c<n;c++)
                    {
                        b[i][j] = p[i+1][c]; 
                    }    
                }
            }
        }
    n = n-1;    
    det = det + m*determinent(n,b);
    }
    }
    return det;
}

2 个答案:

答案 0 :(得分:2)

正如评论中提到的那样,您有无限次递归导致堆栈溢出,因为您将错误的n值传递给了递归调用。您应该传递n--而不是n-1。请注意,传递的值在k循环中不应更改,它应始终比作为函数参数传递的值小1。

在注释中也提到过,k循环的上限在您进行编辑之前已被关闭。

剩下的问题是如何填充子矩阵b[n-1][n-1]。您想要实现的是用b的所有值填充p,除了行0和列k中的值。 c上的循环是不必要的,k == 0的特殊情况也是如此。选择的正确值为b[i][j] = p[i+1][(j < k) ? j : j+1]。换句话说,将行1复制到n-1。对于每一行,将列复制到k的左侧,然后在列索引中添加一个以跳过第k个。

修复这些问题后,代码会为我尝试过的几种情况生成正确的行列式。

答案 1 :(得分:0)

  • 您制作并获得行列式值的2阶矩阵,有逻辑 搞砸了,您陷入无限循环,最后您尝试访问超出范围的数组值,并且发生了核心转储。我已附上以下屏幕截图: 供你参考。 enter image description here