So I have been trying to solve this problem where I have to write a code that counts the number of mines that are around a certain point on a imaginary minefield. Here is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int row;
int col;
int count;
int mineCount = 0;
int i;
int j;
// allocating memory
scanf("%d %d", &row, &col);
char **m = malloc(sizeof(char* ) * row);
for(i = 0; i < row; i ++)
{
m[i] = malloc(sizeof(char) * (col + 1)); //empty minefield
}
//planting mines
for(count = 0; count < row; count ++)
{
scanf("%s", m[count]);
}
// counting mines
for(i = 0; i < row; i ++)
{
for(j = 0; j < (col + 1); j ++)
{
if(m[i][j] != 42)
{
if(m[i-1][j] == 42)
mineCount += 1;
if(m[i+1][j] == 42)
mineCount += 1;
if(m[i][j+1] == 42)
mineCount += 1;
if(m[i][j-1] == 42)
mineCount += 1;
if(mineCount > 0)
m[i][j] = mineCount;
}
}
}
//printing out the minefield
for(i = 0; i < row; i ++)
{
for(j = 0; j < col; j ++)
printf("%c", m[i][j]);
printf("\n");
}
return 0;
}
I put '5 5' for the first input, and for the minefield, my input would be something like this:
*....
..*..
...*..
.*...
....*
at the end though, I get this 'segmentation fault (Core dumped)' error. I have been searching around for answers and found out that this happens when I try to access something that I have no access to. Any help would be appreciated. Thanks.