当前位置: 动力学知识库 > 问答 > 编程问答 >

Segmentation Fault in C associated with a game called Fill-Zone

问题描述:

I'm creating a game which is common known as fill-zone but with numbers. However I'm having issues with segmentation fault. Can you tell me why? Here is my code:

#include

#include

void help(int a[20][60],int b[20][60],int i, int j)

{

if(i-1<20 && i-1>=0 && (i-1!=0 || j!=0) && a[i-1][j]==a[0][0])

{

b[i-1][j]=1;

help(a,b,i-1,j);

}

if(j-1<60 && j-1>=0 && (i!=0 || j-1!=0) && a[i][j]==a[0][0])

{

b[i][j-1]=1;

help(a,b,i,j-1);

}

if(i+1<20 && i+1>=0 && a[i+1][j]==a[0][0])

{

b[i+1][j]=1;

help(a,b,i+1,j);

}

if(j+1<60 && j+1>=0 && a[i][j+1]==a[0][0])

{

b[i][j+1]=1;

help(a,b,i,j+1);

}

}

void game(int a[20][60],int b[20][60],int i,int j)

{

int c;

scanf("%d",&c);

for (i=0;i<20;i++)

for (j=0;j<60;j++)

if (b[i][j]==b[0][0])

a[i][j]=c;

}

int end(int a[20][60])

{

int i,j;

for (i=0;i<20;i++)

for (j=0;j<60;j++)

if (a[i][j]!=a[0][0])

return 1;

return 0;

}

int main(int argc, char *argv[]) {

int a[20][60],b[20][60],i,j,k;

srand (time(NULL));

k=0;

for (i=0;i<20;i++)

for (j=0; j<60; j++)

{

b[i][j]=0;

a[i][j]= rand() % 5 + 1 ;

}

b[0][0]=1;

for (i=0;i<20;i++)

for (j=0; j<60; j++)

{

if (j==59)

printf("%d\n",a[i][j]);

else

printf("%d",a[i][j]);

}

do

{

help(a,b,0,0);

game(a,b,0,0);

for (i=0;i<20;i++)

for (j=0; j<60; j++)

{

if (j==59)

printf("%d\n",a[i][j]);

else

printf("%d",a[i][j]);

}

for (i=0;i<20;i++)

for (j=0; j<60; j++)

{

if (j==59)

printf("%d\n",b[i][j]);

else

printf("%d",b[i][j]);

}

}

while (end(a)==1);

return 0;

}

When I debug it and run it, it works fine for a couple of times but then it says segmentation fault and shows me the line help(a,b,i-1,j);

What should I do? Do you have any suggestions?

网友答案:

You are not checking if both i and j are inside bounds simultaneously -:

In the first if() block, you are not checking if j<60 && j>=0.
Similarly in the second if() block, you are not checking if i<20 && i>=0.
Same for the rest of the 2 if() blocks.

分享给朋友:
您可能感兴趣的文章:
随机阅读: