Firstly, here's what I did to debug (actually I saw the problem in the code and just verified this way, but this will be useful to you).
Add
#include <stdio.h>
and#include <stdlib.h>
at the head of the file.gcc -Wall -O0 -g x.c -o x
to compile with debug and no optimisation.
I then used following to run within 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)
See how in less than 10 seconds it showed me where the error was?
You have two problems:
for (row=1; row<= N;++row){ //Here the things get messy
for ( col = 1 ; col <= M ;++col){
if(p[row][col]=='.'){
The SEGV
appears here as you access p[N][M]
, but the indices of p
can only go from 0
to N-1
and 0
to M-1
respectively. This loop should probably read:
for (row=0; row < N;++row){ //Here the things get messy
for ( col = 0 ; col < M ;++col){
if(p[row][col]=='.'){
(note change to start at row=0
, and row < N
not row <= M
and similarly for col
).
The second problem you have is to do with what to do at the edges:
Lines like this:
if (p[row][col-1]=='*' && col > 1)
count=count+1;
should have the col > 1
condition first so they don't evaluate the array element unless the condition is true. Also, as col
goes 0..M-1
, you want
if ((col > 0) && (p[row][col-1]=='*'))
count=count+1;
Note I've put in some brackets to avoid any ambiguity.
The same applies when looking at the other edges:
if (p[row][col+1]=='*' && col < M)
count=count+1;
should be:
if ((col < M-1) && (p[row][col+1]=='*'))
count=count+1;
That should get you going. But learn to use a debugger.