如何更改函数中的指针? [英] How do i change pointer in function?

查看:50
本文介绍了如何更改函数中的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C 中有一个递归函数,我希望返回的结构指针成为函数中的新结构.我对返回的结构有问题,因为它没有改变.这是我的代码结构:

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.

推荐答案

mystruct 是一个堆栈变量.换句话说,您是按值传递指针,而不是按引用传递.

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

这篇关于如何更改函数中的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆