c++ - 关于结构体指针作为参数传递的疑惑
PHP中文网
PHP中文网 2017-04-17 14:28:01
0
2
592

我在看 《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是原始链表指针的副本,所以在函数内改变它不会有任何损害".
我对这句话中的"副本"感到困惑,函数的参数是个指针类型,不应该是指向同一个地址的变量吗?怎么是个副本呢?
望大神答疑解惑!

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(2)
大家讲道理

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:

struct node *list = xxx;
int n = 10;
search_list(list, n); // 假设这里面把 list 指向 yyy
printf("%d\n", *list == xxx); // 这里 list 还是指向 xxx,所以为 true (输出为 1)

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template