簡體   English   中英

搜索我的二維數組時出現分段錯誤(核心轉儲)錯誤

[英]Getting a segmentation fault (core dumped) error when searching through my 2D array

我正在編寫一段代碼,其中機器人遞歸搜索迷宮以找到正確的路徑。 我相信我已經正確地實現了遞歸函數,但是當我嘗試在主函數中填充二維數組時,我遇到了以下錯誤:分段錯誤(核心轉儲)。 我在下面展示了我的代碼。 我能得到的任何幫助都會有所幫助。 謝謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM