How do i change pointer in function?

后端 未结 1 1834
说谎
说谎 2021-01-24 15:10

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

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-24 15:32

    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 = ;
       ...
    }
    

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

    0 讨论(0)
提交回复
热议问题