通过引用将二维数组传递给函数(C编程)

Sha*_*ack 1 c arrays pointers function multidimensional-array

我正在学习指针,现在卡住了一个小时,用这段代码,

#include <stdio.h>

int determinant(int **mat)  /* int mat[3][3] works fine.. int *mat[3] doesn't.. neither does int *mat[] */
{
    int det;
    int a=*(*(mat+0)+0); // printf("\n%d",a);
    int b=*(*(mat+0)+1); // printf("\n%d",b);
    int c=*(*(mat+0)+2); // printf("\n%d",c);
    int d=*(*(mat+1)+0); // printf("\n%d",d);
    int e=*(*(mat+1)+1); // printf("\n%d",e);
    int f=*(*(mat+1)+2); // printf("\n%d",f);
    int g=*(*(mat+2)+0); // printf("\n%d",g);
    int h=*(*(mat+2)+1); // printf("\n%d",h);
    int i=*(*(mat+2)+2); // printf("\n%d",i);

    det = a*(e*i-h*f) - b*(d*i-g*f) + c*(d*h-e*g);
    return det;
}

int main()
{
    int mat[3][3];
    int i,j;
    printf("Enter the 3 X 3 matrix:\n\n");
    for (i=0;i<3;i++)
    {
        for (j=0;j<3;j++)
        {
            scanf("%d",*(mat+i)+j);
        }
    }
    printf("\nThe determinant of the given 3 X 3 matrix is %d",determinant(mat));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我认为函数调用没有任何问题.也许问题在于接受争论.Idk,不是mat一个指向一维数组的指针,它又是一个指向数组元素mat的指针,指向一个指针?当我在某些地方打印一些文本(只是为了检查)时,我发现执行int det在函数中执行到之后,程序在下一步中崩溃. mat [3][3]运作良好,但我想*在那里使用一些,因为正如我所说,我'正在学习'..

请帮忙!谢谢 :)

Jen*_*edt 6

您的功能的正确原型是

int determinant(int mat[][3]);
Run Code Online (Sandbox Code Playgroud)

要么

int determinant(int (*mat)[3]);
Run Code Online (Sandbox Code Playgroud)

(由于数组作为函数参数的特殊规则,两者都是等价的)

然后你可以简单地访问你的矩阵元素mat[i][j].