我在看 《C语言程序设计 现代方法2》这本书中链表部分的时候有些疑惑.
有这样一个链表:
struct node {
int value;
struct node *next;
};
struct node *first;
struct node *new_node;
first = NULL;
new_node = malloc(sizeof(struct node));
new_node->value = 10;
new_node->next = first;
first = new_node;
new_node = malloc(sizeof(struct node));
new_node->value = 20;
new_node->next = first;
first = new_node;
......
书中有个搜索链表的函数:
struct node *search_list(struct node *list,int n)
{
for (;list != NULL; list = list->next)
if (list->value == n)
return list;
return NULL;
}
然后书中针对这个搜索函数说了这么句话:"因为list是原始链表指针的副本,所以在函数内改变它不会有任何损害".
我对这句话中的"副本"感到困惑,函数的参数是个指针类型,不应该是指向同一个地址的变量吗?怎么是个副本呢?
望大神答疑解惑!
This copy means a copy of the pointer variable itself (not a copy of the pointed content), which means that you can make the list point to anywhere in the function without affecting the point of the list outside the function. For example, there is a place where it is called like this:
So no matter where the list is pointed in search_list, the list pointer variable outside still points to xxx.
Parameters passed to a function will always be copied, no matter what type