Roaming double pointer

I have seen this in some books / textbooks.

When you pass a pointer to the head (linked list) in a function, you need to pass it as a double pointer.

For example: // This means to collapse the linked list, where head points to the first node.

void nReverse(digit **head)
{
    digit *prev=NULL;
    digit *curr=*head;
    digit *next;

    while(curr!=NULL)
    {
        next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    *head=prev;
    return;
}

This works great.

It also works when I use one pointer, for example

void nReverse(digit *head)
{
    digit *prev=NULL;
    digit *curr=head;
    digit *next;

    while(curr!=NULL)
    {
        next=curr->next;
        curr->next=prev;
        prev=curr;
        curr=next;
    }
    head=prev;
    return;
}

I tried to print the list with a pointer to the head. Both functions work fine.

Am I missing something?

Thank,

+3
source share
5 answers

This is very C-like code, not C ++.

Basically, when something is passed by value, the function works with a copy of the data:

void foo(int i)
{
    i = 5; // copy is set to 5
}

int x = 7;
foo(x);
// x is still 7

C :

void foo(int* i)
{
    *i = 5; // whatever i points to is set to 5
}

int x = 7;
foo(&x);
// x is 5

int a digit*. ( .)


++ . . , - :

void foo(int& i) // i is an alias to another value
{
    i = 5; // x is set to 5
}

int x = 7;
foo(x); // pass x as alias, not address of x.
// x is 5

, , , , .

, ++ , std::list.

+4

head=prev; . , , . .

, " "? node , ? ( nReverse(&list); , list, - ( , , node , ...).

+2

, , - "" .

( , , ).

0

, nReverse , node.

head, , node, .

0

( ) , . , , .

digit* list; 
// initialize list
nReverse(&list); 
// now list is pointing to the last element of the chain (and not the first)

, - , NULL, . , .

0

Source: https://habr.com/ru/post/1756068/


All Articles