Search code examples
cpointersrecursionstructuremaze

Passing pointers to structures through recursion (maze solving)


Hey guys so I'm in an intro to computer c programming course at university and we're asked to do a maze solving assignment. I'm writing this piece of code to find the reachability and solution to the maze. I pass a structure M with all the maze elements into it and then use recursion to search the maze. When I call the function within itself I'm not sure what argument to pass because I keep getting an error when I try to pass the argument as assign_reachability(&M). If you have any suggestions or any help I'd appreciate it.

Thanks

int
assign_reachability(maze_t *M){

    int x, y;

    x = M->XP;
    y = M->YP;

    if(M->maze[y][x].exit==EXIT){
        return 1;
    }
    if(M->maze[y][x].type==NOGO || M->maze[y][x].visit==VISIT){
        return 0;
    }
    M->maze[y][x].visit = VISIT;
    /* check not on top row */
    if(y!=0){
        M->YP = (y-1);
        if(assign_reachability(&M))
            M->maze[y][x].reach=REACHABLE;
        return 1;
    }
    /* check not on bottom row */
    if(y!=((M->nrows)-1)){
        M->YP = (y+1);
        if(assign_reachability(&M))
            M->maze[y][x].reach=REACHABLE;
        return 1;
    }
    /* check not on left side */
    if(x!=0){
        M->XP = (x-1);
        if(assign_reachability(&M))
            M->maze[y][x].reach=REACHABLE;
        return 1;
    }
    /* check not on right side */
    if(x!=((M->ncolumns)-1)){
        M->XP = (x+1);
        if(assign_reachability(&M))
            M->maze[y][x].reach=REACHABLE;
        return 1;
    }
    return 0;
}

Solution

  • I keep getting an error when I try to pass the argument as assign_reachability(&M)

    The type of &M is maze_t**, i.e an address of a pointer to maze_t. The function expect its argument to be of type maze_t*,so you should pass it like:

    assign_reachability(M)

    since M is already a pointer to maze_t