Hey guys so Im trying to do a homework and I cant find the fatal error on my program all day long.Let me explain : Firstly,you give the number of rows,col then the cells of the array (only "." for free spaces and "*" for mines, all in one row without spaces) then the crashing happens.
main(){
int i,col,row,count,N,M,j;
char **p;
printf("Give number of rows\n");
scanf("%d",&N);
printf("Give number of columns\n");
scanf("%d\n",&M);
p=malloc(N*sizeof(char *)); //Saving room for the array
if (p==NULL)
return -1;
for (i=0;i < N ; ++i){
p[i] = malloc (M * sizeof(char));
if (*(p+i) == NULL)
return -1;
}
for (i=0; i< N;++i){
for ( j = 0 ; j < M ;++j)
scanf("%c",&p[i][j]); //Insert "*" for mines and the rest with "."
}
for (row=1; row<= N;++row){ //Here the things get messy
for ( col = 1 ; col <= M ;++col){
if(p[row][col]=='.'){
count = 0 ;
if(p[row][col+1]=='*' && col < M)
count=count+1;
if(p[row][col-1]=='*' && col > 1)
count=count+1;
if(p[row+1][col]=='*' && row < N)
count=count+1;
if(p[row-1][col]=='*' && row > 1)
count=count+1;
if(p[row+1][col+1]=='*' && (row < N && col < M))
count=count+1;
if(p[row+1][col-1]=='*' && (row < N && col > 1))
count=count+1;
if(p[row-1][col+1]=='*' && ( row > 1 && col < M))
count=count+1;
if(p[row-1][col-1]=='*' && ( row > 1 && col > 1))
count=count+1;
printf("%d ", count);
}
printf("* ");
}
printf("\n");
}
printf("\n");
for (i=0; i< N;++i){
for ( j = 0 ; j < M ;++j)
printf("%c ",p[i][j]);
printf("\n");
}
for (i = 0 ; i <N ; ++i)
free(p[i]);
free(p);
}
array out of bound
– janiszscanf
. Initialize all variables. Use braces{}
even with single statements afterif
etc. After that start to really hunt for the bug. – hyde