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

2 番目の関数では、prev_node の位置やアドレスを変更していません。データを変更しているだけです。そのため、値を渡すだけで済みます。

于 2014-10-31T19:25:44.083 に答える
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 に答える