开发者

change pointer passed by value

开发者 https://www.devze.com 2023-02-22 06:28 出处:网络
I have given a function foo(struct node *n) where n is the head node in a linked list. Now foo should change n s.t. it points to the end of the li开发者_运维知识库st.

I have given a function foo(struct node *n) where n is the head node in a linked list. Now foo should change n s.t. it points to the end of the li开发者_运维知识库st.

But is this possible with this function signature?

Assuming t is the pointer to the end of the list:

  • n = t won't work because the pointer is passed by value.
  • *n = *t won't work because I would overwrite the head of the list.

Did I miss something?


You would need to use a pointer to a pointer:

foo(struct node **n) 

To change what n points to, you do:

*n = t;


No, because you have a copy of the value of the pointer that's been passed in. You have no access to the original pointer that was passed in. In order to modify the pointer outside the function the sig would need to be foo( struct node **n).


You didn't miss anything. It's not possible with the given function declaration.

As you wrote, the pointer is passed by value, therefore if changed, it won't propagate to the original variable.

You need to change the prototype to foo(struct node **n); or struct node *foo(struct node *n); and return the new pointer as result.


No, you cannot change any argument passed by value.


You can't change n and have the caller see the change. You can change n->prev->next and n->next->prev though - that may be what you need.


It is impossible for the change to be reflected in the calling function. However, inside foo, you can change n to your heart's content.

int foo(struct node *n) {
    n = NULL; /* ok */
}
0

精彩评论

暂无评论...
验证码 换一张
取 消