gpt4 book ai didi

c - 在我的2D数组中搜索时出现段错误(核心转储)错误

转载 作者:行者123 更新时间:2023-12-03 09:05:11 24 4
gpt4 key购买 nike

我正在编写一段代码,其中机器人以递归方式搜索迷宫,以找到到达终点的正确路径。我相信我已经正确实现了递归函数,但是当我尝试在主函数中填充2D数组时,遇到了以下错误:
分段故障(核心已转储)。我在下面显示了我的代码。我能得到的任何帮助都会有所帮助。谢谢!

#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;
}

最佳答案

您的迷宫是6x6的数组,这意味着元素的位置位于[0] [0]至[5] [5]中。

当使x和y等于6时,isValid函数会出现错误。请尝试以下更改:

int isValid(int x, int y) {
return (x >= 0 && x < 6 && y >= 0 && y < 6);
}

关于c - 在我的2D数组中搜索时出现段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60549211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com