2
#include <stdio.h>
int main(void){

    int a=1,b=2,c=3; int *p,*q,**r; p=&a;
    r=&q;
    q=&c;
    a=*q+**r;
    printf("x=%d y=%d z=%d\n",**r,*p,*q); 
    *r=p;
    a=*q+**r;
    printf("w=%d\n",a);
    return 0;
}

Output:

x=3 y=6 z=3
w=12

I was able to predict the output correctly, but I am not sure whether I have the correct explanation for the output of z.

Please see whether I have the correct understanding:

  • Right before *r=p; executes, we have a=6,b=2,c=3.
  • When *r=p; executes, the value at the place to which r points to gets changed to p.
  • Now r points to q that has address of c, so now q has address of a because p points to a. So q now points to a. So *q gives 6.
  • Since r still points to q, and q points to a, **r gives 6.
  • So *q + **r = 6+6=12

Is this the correct explanation?

2 Answers 2

2

Let's break it down:

  1. int a=1,b=2,c=3;

    a = 1
    b = 2
    c = 3
    
  2. int *p,*q,**r;

    p --> ?
    q --> ?
    r --> ? --> ?
    
  3. p=&a;

    p --> a = 1
    q --> ?
    r --> ? --> ?
    
  4. r=&q;

    p --> a = 1
    q --> ?
    r --> q --> ?
    
  5. q=&c;

    p --> a = 1
    q --> c = 3
    r --> q --> c = 3
    
  6. a=*q+**r;, as can be seen from the previous point, we have:

    a = 3 + 3 = 6
    
  7. printf("x=%d y=%d z=%d\n",**r,*p,*q); prints:

    x=3 y=6 z=3
    
  8. *r=p;. This is sneaky: since *r == q, this changes q. This is the same as doing q=p. So we get:

    p --> a = 6
    q --> a = 6
    r --> q --> a = 6
    
  9. a=*q+**r;, as can be seen from the previous point, we have:

    a = 6 + 6 = 12
    
  10. printf("w=%d\n",a); prints:

    w=12
    

Conclusion: your explanation is correct.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes. *r = p would make the item r points to, q, point to the same address as p, which is &a. **r is the same as *q which is the value at &a which is 6.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.