Search code examples
cpointersdouble-pointer

Pointers and double pointers exercise


#include <stdio.h>

 int a;

 int main ()
 {
     int a, b;
     int *p;
     b = 8;
     p = &b;
     a = 32 + b;
     p = &a;
     *p = 32 - b;
     funct (a, &p);
     *p = 2;
     printf ("a=%d b=%d", a, b);
 }

 funct (int x, int **y)
 {
     a = 15;
     **y = x - a;
     *y = &a;
 }

Can someone tell me why a is equal to 9? I tried to solve it but i can't understand it really well

I tried the code in code::blocks and apparently a goes from 40 to 24 after

`*p=32-b`

Also,p=&b means that the pointer points to the address of b,then after a=32+8 p=&a and the double pointer *p= 32-b so *p=24 . Is 24 the address in which the pointer p is stored? because now the value of a should be 24 according to the exercise and I can't understand why.

Can someone tell me step by step how do I deal with those kind of exercise ?


Solution

  • By the time func is called, a=24, and p is the address of a.

    Inside of function, however, a refers to the global a, not the one declared in main. func first assigns that a to be 15. Then:

    • **y is the a in main
    • x - a is main's a (24) minus the global a (15), yielding 9
    • so **y = x - a sets main's a to 9