Yolo
Yolo

Reputation: 39

pointer and pointer clarification

void double_trouble(int *p, int y);
void trouble(int *x, int *y);

int
main(void)
{
    int x, y;
    trouble(&x, &y);
    printf("x = %d, y = %d\n", x, y);
    return (0);
}

void
double_trouble(int *p, int y)
{
    int x;
    x = 10;
    *p = 2 * x - y;
}

void
trouble(int *x, int *y)
{
    double_trouble(x, 7);
    double_trouble(y, *x);
}

For the code above, I know the output of x and y should be 13 and 7. However I'm a little confused that since it's in void, why would the value still stored in the x and y? In other words, since

double_trouble(x, 7);

is called, why the value of x still 13? I mean it's void, the stored value will be deleted, won't it?

If my question is not very clear, please explain a little of function call in the

void trouble(int *, int *)

Upvotes: 2

Views: 68

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

There is some naming confusion going on here. Once you work your way through it, you would see that everything works exactly as it should.

I mean it's void, the stored value will be deleted, won't it?

There are three integer variables in play here: the x and y of main, and x of double_trouble. To distinguish among them, I'll refer to the first two as m::x and m::y, while the last one would be dt::x.

Your trouble function passes pointers to m::x and m::y to double_trouble as a pointer p. In the first call, p refers to m::x, so the assignment

*p = 2 * x - y;

means the same as

m::x = 2 * dt::x - 7;

with 7 coming as a parameter of double_trouble. Since dt::x has been assigned 10 before, this become an assignment m::x = 20 - 7, or simply m::x = 13.

In the second call, y is passed the value of m::x, and p points to m::y, so the same expression corresponds to this:

m::y = 2 * dt::x - m:x;

which is the same as m::y = 20 - 13, or m::y = 7.

Upvotes: 2

mch
mch

Reputation: 9804

p points to the x from main, so writing something to *p also changes the x in main.

That's how pointer work and has nothing to do with the return value of the function.

your trouble(&x, &y); call jumps to the trouble function and assigns the address of the x from main to x in trouble (x in trouble points to x in main). The same happens to y. So the first double_trouble call looks like double_trouble( <the address of x from main>, 7); So p points to x from main and so *p =... changes x from main.

It would be easier to explain and understand if the variables had different names.

Upvotes: 1

Related Questions