How these two lines of pointer execute?

Viewed 52
#include<iostream>
using namespace std;
struct P{
  P *Pptr;
  int i;
};

int main(){
  P p1 = {NULL, 1};
  P p2 = {&p1, 2};
  P p3 = {&p2, 3};

cout << p3.Pptr->Pptr->i << endl;
 cout << p3.Pptr->i << endl;


}

How the lines cout << p3.Pptr->Pptr->i << endl; cout << p3.Pptr->i << endl; executing in the program?

2 Answers

After these statements

P p1 = {NULL, 1};
P p2 = {&p1, 2};
P p3 = {&p2, 3};

you have a chain (due to the data member Pptr)

p3 -> p2 -> p1 -> NULL

So this expression p3.Pptr->Pptr->i at first refers to p2 (p3.Pptr) and then to p1 (p3.Pptr->Pptr) and the value the data member i of the structure p1 is outputted

This expression p3.Pptr->i refers to p2 (p3.Pptr) and its data member i is outputted.

p3.Pptr points to p2
p2.Pptr points to p1
p1.Pptr is NULL

1)cout << p3.Pptr->Pptr->i << endl;

    p3.Pptr->Pptr->i   is  1

2)cout << p3.Pptr->i << endl;

    p3.Pptr->i         is  2
Related