中的分段错误错误所以我一直在试图解决这个问题,我必须编写一个代码来计算一个假想雷区上某个点附近的地雷数量。下面是代码:我的扫雷码在C
#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;
}
我把“5”的第一输入,并为雷区,我的投入将是这样的:在结束
*....
..*..
...*..
.*...
....*
虽然,我得到这'分段错误(核心转储)'错误。我一直在寻找答案,并发现当我尝试访问我无法访问的内容时会发生这种情况。任何帮助,将不胜感激。谢谢。
Plesse的帖子也堆栈跟踪,所以与它出现的线的错误 –
我会建议使用'-g'标志编译代码,然后运行像'gdb'一样的调试器下的可执行文件。这将查明导致段错误的线路。 – hugomg
[请参阅此讨论关于为什么不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –