Is the segmentation fault at the end of the code (just to allocate memory to 2D array and print the result)? The last printf
statement is being printed and any code that I add at the end runs successfully and then segfault appears.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n,i,j,**mat;
printf("\nEnter the size of the square matrix: ");
scanf("%d",&n);
*mat = (int **)malloc(n*sizeof(int *));
for(i=0;i<n;i++)
{
mat[i]= (int *)malloc(n*sizeof(int));
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++) printf("%d\t",mat[i][j]=rand()%10*i+j);
printf("\n\n\n");
}
printf("Bye\n");
return 0;
}
Technically *mat
in 8th line (printed in code) should be mat
, but then everything is fine. The code mentioned compiles (with obvious warning of incompatible pointer type in gcc) and works except at the end when it prints segfault.
Had there been a segfault in the program, it wouldn't had run till the end!