1

I have a recursive function in C and i want the returned struct pointer to become the new struct in the function. Im having a problem with the returned struct because it doesnt change.this is the structure of my code:

struct location_t{
   int x,y;
   location_t * next;
   int dir;
}

location_t * recursive_foo(location_t * loc, maze_t * m){

    int x = loc->x;
    int y = loc->y;
    int dir = loc->dir;

    loc->next = malloc(sizeof(location_t));
    location_t * temp = loc->next;

    if(m->map[--x][y] != '#' && dir != 0){
        temp->x = x;
        temp->y = y;
        temp->dir = 2;
        loc = recursive_foo(temp);
    }
    if(m->map[--x][y] != '#' && dir != 1){
        temp->x = x;
        temp->y = y;
        temp->dir = 3;
        loc = recursive_foo(temp);
    }
    if(m->map[--x][y] != '#' && dir != 2){
        temp->x = x;
        temp->y = y;
        temp->dir = 0;
        loc = recursive_foo(temp);
    }
    if(m->map[--x][y] != '#' && dir != 3){
        temp->x = x;
        temp->y = y;
        temp->dir = 1;
        loc = recursive_foo(temp);
    }

    return loc;

}   

Im having a problem with the returned struct because it doesnt change.

It is meant to stack these structs by referring to each other.

2
  • 3
    Can you post a minimal working program? What you've posted has typos that will fail to compile, and not enough logic to find the bug. Commented Mar 24, 2013 at 11:03
  • Make sure x doesn't become negative! You really wouldn't want m->map[-1].... Commented Mar 24, 2013 at 11:30

1 Answer 1

2

mystruct is a stack variable. In other words, you are passing the pointer by value, instead of passing it by reference.

What have you done at the moment is essentially the same as:

int f(int i) {
   ...
   i = <any value>;
   ...
}

In this case you are modifying only a copy of the value.

In your program, you are also modifying a copy of the pointer. Outside of the function the pointer stays not modified.

If you want to modify it, you need to pass a pointer to it:

location_t * recursive_foo(location_t** loc, maze_t * m){
    int x = (*loc)->x;
    int y = (*loc)->y;
    int dir = (*loc)->dir;
    ...
    *loc = recursive_foo(&temp);
    ...
    return *loc;
}
Sign up to request clarification or add additional context in comments.

1 Comment

But if i make a ** out of temp how do i assign the vars x, y and dir?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.