Kelsius
Kelsius

Reputation: 473

Realistic uses for pointer to pointer to pointer?

I've seen example codes in books that demonstrate pointers such as int*** ptr, int ****ptr, etc. What are some real life examples that this would be used ?

Upvotes: 2

Views: 178

Answers (4)

John Bode
John Bode

Reputation: 123558

Another place where you will run into multiple levels of indirection is when you need a function to write to a pointer parameter. Assume the following code:

void bar( T *arg )
{
  *arg = new_value(); // write new value to what arg points to
}

void foo( void )
{
  T x;
  bar (&x);  // write new value to x
}

Substitute T with a pointer type Q *:

void bar( Q **arg )
{
  *arg = new_value(); // write new value to what arg points to
}

void foo( void )
{
  Q *x;
  bar (&x);  // write new value to x
}

Substitute Q with another pointer type R *:

void bar( R ***arg )
{
  *arg = new_value(); // write new value to what arg points to
}

void foo( void )
{
  R **x;
  bar (&x);  // write new value to x
}

etc., etc., etc.

The semantics are the same in all three cases; we're writing a new value to x. The only thing that changes is the type of x, and the number of levels of indirection.

Upvotes: 1

Mike Nakis
Mike Nakis

Reputation: 62054

Such pointers are extremely rarely used, and I would be willing to bet that in the vast majority of the cases where they are used, they could have been avoided by restructuring the code to make it more simple. (And also more understandable and more maintainable.)

However, pointers (*p) and pointers to pointers (**p) are very common, which means that the language has to offer the ability to declare at least those, so there is absolutely no reason to put an arbitrary limit at two levels of indirection and forbid anyone from declaring any more levels of indirection.

Upvotes: 4

Drax
Drax

Reputation: 13288

The most i've ever used is char***.

I was parsing a file and had to split it in words per lines.

So you had :

char*** parsed_file;
char** first_line = parsed_file[0];
char* first_word_of_first_line = first_line[0];

Upvotes: 1

flogram_dev
flogram_dev

Reputation: 42858

They are mostly used for dynamically allocated multi-dimensional arrays.

Example:

int width = 100, height = 2, depth = 50;
int*** array3d;
array3d = new int**[width];
for (int x = 0; x < width; ++x) {
    array3d[x] = new int*[height];
    for (int y = 0; y < height; ++y) {
        array3d[x][y] = new int[depth];
    }
}

// Now array3d can be used like this:
array3d[42][0][1] = 666;

Upvotes: 8

Related Questions