问题
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 list.
But is this possible with this function signature?
Assuming t is the pointer to the end of the list:
n = twon\'t work because the pointer is passed by value.*n = *twon\'t work because I would overwrite the head of the list.
Did I miss something?
回答1:
You would need to use a pointer to a pointer:
foo(struct node **n)
To change what n points to, you do:
*n = t;
回答2:
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).
回答3:
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.
回答4:
No, you cannot change any argument passed by value.
回答5:
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.
回答6:
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 */
}
来源:https://stackoverflow.com/questions/5531765/change-pointer-passed-by-value