When allocating memory for the 2-dimensional array using malloc()
,segmentation fault occurs when the input size(matrix N*N) is more than 5
(i.e., N>5
).
The below code is working fine for inputs(N) less than 5
.
Could you please help me out in figuring the problem?
#include<stdio.h>
#include <stdlib.h>
int main(){
int n;
int i,j;
int **adj;
//reading size of a N*N matrix
scanf("%d",&n);
//dynamically allocating memory for a 2-dimensional array
adj=(int**)malloc(sizeof(int)*n);
for(i=0;i<n;i++){
adj[i]=(int*)malloc(sizeof(int)*n);
}
//taking input from the file
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf("%d",&adj[i][j]);
}
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d\t",adj[i][j]);
}
printf("\n");
}
return 0;
}