Reputation: 81
#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 ?
Upvotes: 0
Views: 495
Reputation: 310990
Before this call
funct (a, &p);
the variable a
is equal to 24 due to this statement
*p = 32 - b;
where b
is equal to 8.
Inside the function in this statements
a = 15;
**y = x - a;
a
is set to 24 - 15
that is equal to 8
because the dereferenced pointer *y
points to the original variable a
.
Upvotes: 0
Reputation: 49803
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**y = x - a
sets main
's a
to 9Upvotes: 5