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);
}