Linked list head double pointer passing

前端 未结 5 2303
一生所求
一生所求 2020-12-17 05:21

I have seen this in some book/ tutorial.

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

For eg:

5条回答
  •  清酒与你
    2020-12-17 06:05

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

    Basically, when something is passed by-value the function operates on 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
    

    In C, you instead pass a pointer to the variable, and can change it that way:

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

    For you, instead of an int it's a digit*. (Resulting in a pointer to pointer.)


    In C++, references were introduced. A reference is an alias to another object. So you'd do something like this:

    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
    

    A reference is generally preferred, since it enforces that you actually refer to an object, and simplifies both calling and operating code.

    Of course in C++ you wouldn't implement a list yourself, you'd use std::list.

提交回复
热议问题