与指针概念的指针混淆

时间:2014-10-31 19:10:51

标签: c++ pointers linked-list pointer-to-pointer

传递指针基本上就像将指针作为值传递..函数内部对指针的更改不会修改指针的实际值..但是当我们需要访问函数中的实际指针本身时,然后我们想出指针概念的指针。这是我的理解......

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

            void push(struct node** head_ref, int new_data) // i understand the need of pointer to pointer here, since we are changing the actual value by adding a node..
            {
                struct node* new_node = (struct node*) malloc(sizeof(struct node));
                new_node->data  = new_data;
                new_node->next = (*head_ref);
                (*head_ref)    = new_node;
            }

            void insertAfter(struct node* prev_node, int new_data) // why are we not using pointer to pointer here since even here the pointer data is getting modified..??
            {
                if (prev_node == NULL)
                {

                  return;
                }

                struct node* new_node =(struct node*) malloc(sizeof(struct node));
                new_node->data  = new_data;
                new_node->next = prev_node->next;
                prev_node->next = new_node;
            }

            int main()
            {
                struct node* head = NULL;

                append(&head, 6);
                insertAfter(head->next, 8);

                return 0;
             }

请澄清.. 我很困惑为什么我们没有在InsertAfter(...)中使用指针指针,因为我们认为我们在那里更改了指针?

3 个答案:

答案 0 :(得分:0)

您在开始时是正确的,但通常如果您想要更改原始值,则通过引用(&)而不是值(*)传递指针

以下是需要阅读的内容: http://courses.washington.edu/css342/zander/css332/passby.html

答案 1 :(得分:0)

在第二个函数中,您没有修改prev_node位置或地址,只是更改数据。所以你只需要传递值。

答案 2 :(得分:0)

不同之处在于函数对传入的内容的作用。

这会修改*head_ref本身指向的内容:

void push(node** head_ref, int new_data);

虽然这会修改node指向的prev_node的内容,但它仍然会指向相同的node

void insertAfter(node* prev_node, int new_data);

查看实际用法也会清除这一点:

// head points to the node 0
node* head = new head{0, nullptr}; 

// head now points to the node 5, which itself points to the node 0
// so our list is {5} --> {0}
push(&head, 5); 
     ^
     additional clue that we are modifying head

// head->next points to the node 0 before this
// it **still** continues to point to that node after the call, but we 
// change what comes after it, to now be a new node 3
// so our list is {5} --> {0} --> {3}
insertAfter(head->next, 3);

// head is still the 5. head->next is still the 0.