This is my code for the creation of a grid similar to that of the game "mines":
#include <stdio.h>
#include <stdlib.h>
int main(){
int nr, nc, ** mtx, i, j;
//Matrix costruction
FILE * inStr;
inStr = fopen("brasa.dat","r");
if(inStr == NULL){
printf("\nProblem while opening the file.\n");
return 1;
}
fscanf(inStr, "%d%d", &nr, &nc);
mtx = (int**) malloc(nr * sizeof(int*));
if(mtx == NULL){
printf("\nMemory allocation error.\n");
return 1;
}
else{
for(i = 0; i < nr; i++)
mtx[i] = (int*) malloc(nc * sizeof(int));
if(mtx[i] == NULL){
printf("\nMemory allocation error.\n");
return 1;
}
}
//Filling matrix
for(i = 0; i < nr; i++){
for(j = 0; j < nc; j++)
mtx[i][j] = 0;
}
while(!feof(inStr)){
fscanf(inStr,"%d %d",&i,&j);
mtx[i][j] = 9;
}
fclose(inStr);
for(i = 0; i < nr; i++){
for(j = 0; j < nc; j++){
if(i == 0){
if(j == 0){
if(mtx[i][j+1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j+1] > 8)
mtx[i][j]++;
}
else if(j == nc-1){
if(mtx[i][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j] > 8)
mtx[i][j]++;
}
else{
if(mtx[i][j-1] > 8)
mtx[i][j]++;
else if(mtx[i][j+1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j+1] > 8)
mtx[i][j]++;
}
}
else if(i == nr-1){
if(j == 0){
if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j+1] > 8)
mtx[i][j]++;
else if(mtx[i][j+1] > 8)
mtx[i][j]++;
}
else if(j == nc-1){
if(mtx[i][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j] > 8)
mtx[i][j]++;
}
else{
if(mtx[i][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j+1] > 8)
mtx[i][j]++;
else if(mtx[i][j+1] > 8)
mtx[i][j]++;
}
}
else if(j == 0){
if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j+1] > 8)
mtx[i][j]++;
else if(mtx[i][j+1] > 8)
mtx[i][j]++;
else if(mtx[i-1][j+1] > 8)
mtx[i][j]++;
else if(mtx[i-1][j] > 8)
mtx[i][j]++;
}
else if(j == nc-1){
if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i][j-1] > 8)
mtx[i][j]++;
else if(mtx[i-1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i-1][j] > 8)
mtx[i][j]++;
}
else{
if(mtx[i-1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j-1] > 8)
mtx[i][j]++;
else if(mtx[i+1][j] > 8)
mtx[i][j]++;
else if(mtx[i+1][j+1] > 8)
mtx[i][j]++;
else if(mtx[i][j+1] > 8)
mtx[i][j]++;
else if(mtx[i-1][j+1] > 8)
mtx[i][j]++;
else if(mtx[i-1][j] > 8)
mtx[i][j]++;
}
if(mtx[i][j] > 8)
printf("*\t");
else
printf("%d\t", mtx[i][j]);
}
}
free(mtx);
return 0;
}
During the execution of the program appears a segmentation fault. Doing several tests I noticed that the problem should be between line 85 and line 158. Can you help me?