简体   繁体   English

当按值传递指针时,内部会发生什么?

[英]What happens internally when passing a pointer by value?

Suppose I have a following linked list structure: 假设我具有以下链接列表结构:

struct linked_list
{
    struct linked_list *next;
    int data;
};
typedef struct linked_list node;

And the following function to print the linked list: 并使用以下功能来打印链表:

void print(node *ptr)
{
    while(ptr!=NULL)
    {
        printf("%d ->",ptr->data);
        ptr=ptr->next;
    }
}

Now in the main() function when I write this: 现在在main()函数中,当我编写此代码时:

print(head); // Assume head is the pointer pointing to the head of the list

This is essentially call-by-value. 这本质上是按值调用。 Because ptr in print will receive a copy of head . 因为print ptr将收到head的副本。 And we can't modify head from the print() function because its call-by-value. 而且我们无法通过print()函数修改head ,因为它是按值调用的。

But my doubt is, since ptr receives a copy of head but it's able to print the value of linked list. 但是我的疑问是,由于ptr收到head的副本,但是它能够打印链接列表的值。 So does that means the print() function receives whole copy of linked list? 那么,这是否意味着print()函数会收到链表的完整副本? If it does not receives the whole copy of linked list how its able to print the list? 如果没有收到链表的整个副本,它如何打印链表?

Your function receives a copy of the pointer. 您的函数将收到指针的副本。 The copy of the pointer points to the same place as the original pointer. 指针的副本指向与原始指针相同的位置。

A pointer is like an address. 指针就像一个地址。 Here's an analogy. 这是一个比喻。 Imagine writing your address down on a piece of paper. 想象一下将您的地址写在一张纸上。 When you want to give it to a friend you copy the address: that is, you write the same address on a new piece of paper and give that paper to your friend. 当您想将其提供给朋友时,您可以复制地址:也就是说,您将相同的地址写在一张新纸上,然后将该纸给您的朋友。 But if they go to the address written on their copy, they'll go to the exactly same place as if they had gone to the address on the original piece of paper. 但是,如果他们转到复印件上写的地址,他们将到达与原纸上的地址完全相同的位置。

print receives a copy of the address of head, which means that the data representing head isn't copied: the function is using the actual head and hence the actual linked list, not a copy. print收到head的地址的副本,这意味着不复制代表head的数据:该函数使用的是实际的head,因此使用的是实际的链表,而不是副本。

The implications are that you can change head , eg head->data , and you can modify the rest of the linked list. 含义是您可以更改head ,例如head->data ,并且可以修改链接列表的其余部分。 The only thing that you can't do is change which node your passed-in pointer points to, ie you can't do head = NULL in print and expect that to be reflected outside print . 你不能做的唯一的事情就是变化哪个节点的传入的指针指向,即你不能做head = NULLprint并期望外界反映print

So, any of the following changes are all reflected outside the function: 因此,以下任何更改都反映在函数外部:

// pick one:
ptr->data = 20;
ptr->next = NULL;
ptr->next = malloc(sizeof(node));
ptr->next->data = 20;
// etc.

The following aren't : 以下不是

ptr = NULL;
ptr = malloc(sizeof(node));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM