0

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

            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(...) 中使用指向指针的指针,以及认为我们在那里更改了指针?

4

3 回答 3

0

一开始你是正确的,但通常如果你想改变原始值,那么你通过引用(&)而不是通过值(*)传递指针

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

于 2014-10-31T19:13:42.203 回答
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. 
于 2014-10-31T19:29:38.823 回答
0

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

于 2014-10-31T19:25:44.083 回答