I'm new to c language and I have an assignment to allocate a dymanic matrix inside a function, put values in it and return to main and then call to another function that prints the matrix. I know that if I want to change the matrix values inside a function I need to use '&'. But when I return to main in order to print the matrix I get "Segmentation fault (core dumped)". Can somone tell me what's wrong with my code:
#include <stdio.h>
#include <stdlib.h>
int checkSize(int); //checking matrix size
void printMatrix(int **, int); //print matrix
int createMatrix(int ***, int); //allocate matrix and puts values from user.
int main()
{
int c; int **p=NULL;
printf("enter size of a matrix\n");
c=getchar();
if (checkSize(c))
{
if((createMatrix(&p, c-'0'))!=0)
printMatrix(p, c-'0');
}
return 0;
}
int checkSize(int c)
{
if (c>'9'||c<'0')
return 0;
return 1;
}
int createMatrix(int ***p, int n)
{
int m=n;
int k;
p=(int***)malloc(m*sizeof(int**));
for (k=0; k<m; k++)
p[k]=(int**)malloc(m*sizeof(int*));
printf("enter numbers\n");
int *l;
int i;
int c;
for (i=0; i<m; i++)
{
k=n;
for (l=(int*)(p)+i;k>0;l++)
{
c=getchar();
if (c==EOF)
{
printf("error EOF");
return 0;
}
if (c>'9'||c<'0')
{
printf("error");
return 0;
}
*l=c-'0';
k--;
}
}
return 1;
}
void printMatrix(int **p, int n)
{
int k=n;
int* l;
int i;
int m=n;
for (i=0; i<k; i++)
{
m=n;
printf("\n");
for (l=(int*)(p)+i;m>0;l++)
{
printf("%d ", *l);
m--;
}
}
}