[英]Getting a segmentation fault (core dumped) error when searching through my 2D array
I am working on a piece of code where a robot recursively searches through a maze to find the correct path to the end.我正在编写一段代码,其中机器人递归搜索迷宫以找到正确的路径。 I believe I have properly implemented the recursive function, however when I try to fill the 2D array in my main function I run into the following error: Segmentation Fault (core dumped).我相信我已经正确地实现了递归函数,但是当我尝试在主函数中填充二维数组时,我遇到了以下错误:分段错误(核心转储)。 I have shown my code below.我在下面展示了我的代码。 Any help I could get would be helpful.我能得到的任何帮助都会有所帮助。 Thank you!谢谢!
#include <stdio.h>
#include <string.h>
int isValid(int x, int y)
{
if(x >= 0 && x <= 6 && y >=0 && y <= 6)
{
return 1;
}
return 0;
}
int mazeGo(char maze[6][6], char solution[6][6], int x, int y)
{
char mazeFull [6][6] =
{
{'.','#','#','#','#','#'},
{'.','.','.','.','.','#'},
{'#','.','#','#','#','#'},
{'#','.','#','#','#','#'},
{'.','.','.','#','.','.'},
{'#','#','.','.','.','#'}
};
//checks to sse if the robot is at the goal
if(x == 5 && y == 4 && isValid(x,y) == 1)
{
printf("Maze had been Solved");
solution[x][y] = '.';
return 1;
}
else if(x != 5 && y != 4 && isValid(x,y) == 1)
{
//Robot travels north
if(mazeGo(mazeFull,solution,x,y-1) == 1)
{
solution[x][y] = '.';
return 1;
}
//Robot travels East
else if(mazeGo(mazeFull,solution,x+1,y) == 1)
{
solution[x][y] = '.';
return 1;
}
//Robot travels south
else if(mazeGo(mazeFull,solution,x,y+1) == 1)
{
solution[x][y] = '.';
return 1;
}
//Robot travels west
else if(mazeGo(mazeFull,solution,x-1,y) == 1)
{
solution[x][y] = '.';
return 1;
}
else
{
solution[x][y] = '#';
return 0;
}
}
return 0;
}
int main()
{
int x = 0;
int y = 0;
char solution[6][6];
char maze [6][6] =
{
{'.','#','#','#','#','#'},
{'.','.','.','.','.','#'},
{'#','.','#','#','#','#'},
{'#','.','#','#','#','#'},
{'.','.','.','#','.','.'},
{'#','#','.','.','.','#'}
};
if(mazeGo(maze,solution,x,y) == 1)
{
for(int r = 0; r < 6; r++)
{
for(int c = 0; c < 6; c++)
{
printf("%c \n", solution[r][c]);
}
}
}
/*else
{
printf("There is no solution");
}*/
return 0;
}
Your maze is an array of 6x6 that means the positions to elements are located in [0][0] to [5][5].你的迷宫是一个 6x6 的数组,这意味着元素的位置位于 [0][0] 到 [5][5]。
Your isValid function have a bug when it let x and y be equal to 6. Try the change bellow:当让 x 和 y 等于 6 时,您的 isValid 函数有一个错误。尝试以下更改:
int isValid(int x, int y) {
return (x >= 0 && x < 6 && y >= 0 && y < 6);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.