use*_*944 2 c dev-c++ minesweeper
嘿伙计,所以我想做一个功课,我不能整天找到我的程序上的致命错误.让我解释一下:首先,你给出行数,col然后数组的单元格(只有"."免费空间和"*"表示矿井,所有行都没有空格)然后发生崩溃.
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);
}
Run Code Online (Sandbox Code Playgroud)
首先,这是我调试的内容(实际上我在代码中看到了问题并且只是通过这种方式进行了验证,但这对您有用).
添加#include <stdio.h>并#include <stdlib.h>在文件的头部.
gcc -Wall -O0 -g x.c -o x 用debug编译而不是优化.
然后我用以下来运行gdb:
gdb x
...
(gdb) run
Starting program: /home/amb/so/x
warning: no loadable sections found in added symbol-file system-supplied DSO at 0x7ffff7ffa000
Give number of rows
1
Give number of columns
1
.
Program received signal SIGSEGV, Segmentation fault.
0x00000000004007d4 in main () at x.c:25
25 if(p[row][col]=='.'){
(gdb) print row
$1 = 1
(gdb) print col
$2 = 1
(gdb)
Run Code Online (Sandbox Code Playgroud)
看看它如何在不到10秒的时间内向我显示错误的位置?
你有两个问题:
for (row=1; row<= N;++row){ //Here the things get messy
for ( col = 1 ; col <= M ;++col){
if(p[row][col]=='.'){
Run Code Online (Sandbox Code Playgroud)
在SEGV这里会显示您所访问p[N][M],但该指数p只能去0到N-1和0来M-1分别.这个循环可能应该是:
for (row=0; row < N;++row){ //Here the things get messy
for ( col = 0 ; col < M ;++col){
if(p[row][col]=='.'){
Run Code Online (Sandbox Code Playgroud)
(注意改变开始row=0,而row < N不是row <= M和类似的col).
你遇到的第二个问题是在边缘做什么:
像这样的行:
if (p[row][col-1]=='*' && col > 1)
count=count+1;
Run Code Online (Sandbox Code Playgroud)
应该首先具有col > 1条件,因此除非条件为真,否则它们不会计算数组元素.此外,由于去,你想col0..M-1
if ((col > 0) && (p[row][col-1]=='*'))
count=count+1;
Run Code Online (Sandbox Code Playgroud)
注意我放了一些括号以避免任何歧义.
查看其他边缘时也是如此:
if (p[row][col+1]=='*' && col < M)
count=count+1;
Run Code Online (Sandbox Code Playgroud)
应该:
if ((col < M-1) && (p[row][col+1]=='*'))
count=count+1;
Run Code Online (Sandbox Code Playgroud)
这应该让你去.但学会使用调试器.