c - Why does this code gives segmentation fault with some inputs? -
//difference of 2 diagonals of n x n matrix #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main() { int n, j, i,k,l; scanf("%d",&n); int array[n-1][n-1], sum1=0, sum2=0, sum=0; for(i=0;i<n; i++) { for(j=0; j<n; j++) { scanf("%d",&array[i][j]); } } for(k = 0; k<n; k++){ sum1 += array[k][k]; } for(l=0; l<n; l++){ sum2 += array[n-1-l][l]; } sum = abs(sum1 - sum2); printf("%d",sum); return 0; }
the above code generates segmentation fault inputs. program calculates absolute difference between summation of values in 2 main diagonal.
the main problem, think, you're declaring array of size n - 1
× n - 1
, filling in n
elements. try declaring n
×n
.
Comments
Post a Comment