Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To what use is multiple indirection in C++?

Tags:

c++

pointers

Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in Foo **) in C++?

like image 625
Tommy Herbert Avatar asked Sep 16 '08 10:09

Tommy Herbert


People also ask

What is multiple indirection in C?

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.

What is the use of indirection operator in C?

The * (indirection) operator determines the value referred to by the pointer-type operand. The operand cannot be a pointer to an incomplete type. If the operand points to an object, the operation yields an lvalue referring to that object.

What is use of double pointer in C?

The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer. That is why they are also known as double pointers.

What is indirection in C programming?

The indirection operator is a unary operator that can be used to obtain the value stored at the memory location referenced by a pointer variable. The indirection operator must precede the pointer variable name, with no intervening space.


1 Answers

Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns.

#include <iostream>

using namespace std;

struct Foo {
    int a;
};

void CreateFoo(Foo** p) {
    *p = new Foo();
    (*p)->a = 12;
}

int main(int argc, char* argv[])
{
    Foo* p = NULL;
    CreateFoo(&p);
    cout << p->a << endl;
    delete p;
    return 0;
}

This will print

12

But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output.

#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    const char* words[] = { "first", "second", NULL };
    for (const char** p = words; *p != NULL; ++p) {
        cout << *p << endl;
    }

    return 0;
}
like image 197
Jorge Ferreira Avatar answered Sep 24 '22 09:09

Jorge Ferreira