You are here:

C++/Pointers to pointers - Mulitple Indirection

Advertisement


Question
I am trying to use multiple indirection in a function.  Two of my parameters are pointers to another pointer in my main module. I am having difficulty understanding this topic in reference to linked lists.  I know that a copy is being passed unless multiple indirection is used.  I also know that the reference (&) operator needs to be used with the parameter when the function is called.  However I do not understand how to directly change the value of the original pointer.  Could you explain the topic in simple terms for me so I can better understand it?  I've included basic code so you can see what I am attempting to do.  Thank you for your time.

void insertNewWord(TWord **begin, TWord **end, TWord * previous, TWord * newWord)
{
    printf(newWord->m_word);
    printf ("t");

    if (begin == NULL || previous == NULL)
    {
       *begin = newWord;
       newWord->next = *begin;
       if (*end == NULL)
       {
         *end = newWord;
       }
    }
    else
    {
       newWord->next = previous->next;
       previous->next = newWord;
    }
    printf("n");
}

int main()
{
   insertNewWord(&start_ptr, &end_ptr, prev, curr);
}  

Answer
Pointers and references are interchangeable.  If your argument is *x, you modify the parameter (&variable) by assigning to *x.  If you pass in a reference &x, you modify the parameter variable by assigning to x.  A reference really just makes the syntax a little easier.

void insertNewWord(TWord * &begin, TWord * &end, TWord * previous, TWord * newWord)
{
.
.
.
}

You change begin by assigning to it directly instead of using *begin = nextWord;  Use the function definition above and remove the * on begin and end in the code.

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.