-1

Here i have written a code to print out the sum of diagonal values of a 3x3 matrix.Here I have to pass the matrix to a function .The matrix is passed to an array of pointers.Code works but the problem is I have to write the parameter in the following manner

int (*mat)[3]

the following causes the program to crash

int *mat[3]

I would like to know what is the difference between the two? and why the second one causes the program to crash ?

Full Code :

#include<stdio.h>

int main(){

    int mat[3][3];
    int i,j;
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            printf("input row %d column %d = ",i+1,j+1);
            scanf("%d",&mat[i][j]);
            printf("\n");
        }

    }


    // task 1 : Display sum of diagonal values
    diagonal_sum(mat);

}

diagonal_sum(int (*mat)[3]){  // pointer to a 2d array

    printf("\n    DIAGONAL SUM    \n");
    int sum=0;
    int i;
    for(i=0;i<3;i++){
        sum+=*(*(mat+i)+i);  // access the diagonal values of the matrix
    }

    printf("\ndiagonal sum is = %d \n",sum);
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • 1
    Never write this `sum+=*(*(mat+i)+i);` it's comepletely unnecessary, Just write the way more readable `mat[i][i]`. – Iharob Al Asimi May 15 '16 at 11:11
  • 1
    They bind differently. `*mat[3]` is the same as `*(mat[3])`, which is obviously quite different from `(*mat)[3])`. – Tom Karzes May 15 '16 at 11:15
  • 1
    You should get compiler errors or warnings in the "crash" case. These cannot be ignored. Running a program that produces this sort of error/warning is pointless – M.M May 15 '16 at 11:16
  • "*`// pointer to a 2d array`*" no, `int (*mat)[3]` is a pointer to an `int[3]`, to an array of 3 `int`s. That is, as per your code, a pointer to the 1st element of the 2D-array `mat[3][3]`. As when you pass an array to a function it *decays* to a pointer to its 1st element. :-) Note: In C a 2D-array is just nothing else than an array of arrays. – alk May 15 '16 at 11:31
  • 1
    Strongly related: http://stackoverflow.com/questions/859634/c-pointer-to-array-array-of-pointers-disambiguation – alk May 15 '16 at 11:36

1 Answers1

3

In case you're writing

 int (*mat)[3]

it means mat is a pointer to an array of 3 ints.

On the other hands,

int *mat[3]

means, mat is an array of 3 int *s (pointer to integers).

Clearly these two are different types. So, your pointer arithmetic goes wrong.

Now, you can understand, your comments, // pointer to a 2d array, is not correct.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261