How does this multiple indirection work?

#include<iostream>
#include<conio.h>
using namespace std; 
int main()
{
    int i=10, j=20, k=30;
    int *ip1, *ip2, **ipp;
    ip1=&i;
    ip2=&j;
    ipp=&ip1;
    *ipp=ip2;
    *ipp=&k;
    cout<<*ip1<<endl;
    cout<<*ip2<<endl;
    cout<<**ipp;
    getch();
}

The line cout<<*ip1;prints 30 to the console, can anyone explain how? Output signal -

30
20
30

I expected -

10
20
30

I do not know how multiple indirectness works in this case.

+4
source share
2 answers

The variable ipppoints to the variable ip1because of this statement

ipp=&ip1;

Thus, any dereferencing of a pointer ippgives the value of a pointer ip1. So, for example, this statement

*ipp=ip2;

equivalently

ip1 = ip2;

and this statement

*ipp=&k;

equivalently

ip1 = &k;

As a result, it ip1contains the address of the variable k, but it ippcontains the address of the variable itself ip1.

And these statements

cout<<*ip1<<endl;
//...
cout<<**ipp;

, , < < endl . k.

0

cout < < * ip1; 30 , - , ?

ip1 ipp ( ), i, j, , , k.

ipp=&ip1;         // make ipp point to ip1
*ipp=ip2;         // dereference on ipp, change the value of pointee (i.e. ip1) to ip2
                  // i.e. make ip1 point to j
*ipp=&k;          // change the value of pointee (i.e. ip1) to the address of k
                  // i.e. make ip1 point to k
cout<<*ip1<<endl; // now we get 30 (i.e. the value of k)
+2

Source: https://habr.com/ru/post/1649138/


All Articles