Search code examples
c++elementpointer-to-pointer

How to use pointer-to-pointer's variables?


I am trying this code:

int x[] = {1,5};
int y[] = {3,6};
int *w[] = {x,y};
int **z = w;


printf("%d", **z[1]);
cout<<**z[0];

But it doesn't work. My goal is to access to each element inside the x or y arrays. My question comes from this part of a really OpenCV code:

float h_ranges[] = {0, 180}; 
float s_ranges[] = {0, 256};
const float* ranges[] = {h_ranges, s_ranges};

And like to know how is it possible to read each element inside ranges[]?

EDIT: I tryed:

printf("%d", z[1][1]);
cout<<z[0][0];

And it worked, but it's interesting for me to know why

printf("%d", **z[1][1]);
cout<<**z[0][1];

Doesn't work, but the following code works

printf("%d", *w[1]);
cout<<*w[0];

What is the difference between w and z here?

EDIT2:

Why the result of

printf("%d", *w[1]);
cout<<*w[0];

Is same as the result of:

printf("%d", *z[1]);
cout<<*z[0];

Solution

  • Why z[1][1] works?

    z is a pointer to pointer to int in w array. Dereferencing *z will give you pointer to the 1st int in {1,5} and dereferincing it once more **z will give you that int, which is 1. This is identical to doing z[0][0] or *(*(z + 0) + 0).

    z[1][1] is the same as *(*(z + 1) + 1). Dereferencing *(z + 1) will give you the pointer to the first int in the second array {3,6}. Incrementing *(z + 1) + 1 will give you the pointer to the second int in the second array {3,6}, Dereferencing *(*(z + 1) + 1) will give you the actual second int of the second array {3,6}, which in your case is 6;

    Why **z[1][1] doesn't work?

    With z[1][1] will get you an int (see above), 6 in your example. So what happens when you try to dereference an int, let alone twice? An error!

    Why *w[1] works?

    w is array of pointers. With w[1] you get the second pointer from that array which points to the array of 2 ints, {3,6}. If you dereference it, you will get the 1st int of that array, which in your case is 3.

    Why the result of *w[1] is same as the result of *z[1]?

    Let's visualize it:

    {1,5} {3,6}
     |     |
    {w[0], w[1]}
     |     | 
     z     z+1
    

    Array w is array of 2 pointers to int, which are w[0] and w[1]. w[1] is the second pointer to int in that array. The int it points to is 3. z is a pointer to pointer to int, or in this case pointer to w[0], which is pointer to 1. z[1] is the same as *(z+1) and it makes z to point to the next pointer before dereferencing result, which in this case is w[1], which points to 3. Dereferencing both w[1] and z[1] yields the same result, because ultimately they both point to the same int, which is 3.