Reputation: 15
I was practising with pointers and came across this thing.
The following code gives the answer:
1
0
3
when I change *a with *c the answer is same but on changing with *b=0, the answer is
1
2
0
Can you please what is going on behind the scenes in each of these processes?
#include<iostream>
using namespace std;
void func(int *a, int *b,int *c)
{
a=b;
b=c;
c=a;
*a=0;
}
int main()
{
int a=1,b=2,c=3;
func(&a,&b,&c);
cout<<a<<endl<<b<<endl<<c;
}
Upvotes: 0
Views: 97
Reputation: 1845
You are first swapping pointers; the only relevant line is:
a=b;
So the variable a
in func
now points to the address of b
in your main.
Then
*a=0;
sets the value of the variable a
in func
is pointing to (which is b
in your main now) to 0
.
So, a
, b
, c
are pointers to things, while a
, b
, c
are "things". It become easier when you rename the variables in func
to something else, for example: pa
, pb
and pc
as "pointer-to-a". Then you can see you are swapping pointers and that *pa=0
is "setting the value pa
is pointing to to 0
.
Keeping this in mind, it should become clear that modifying your code will swap pointers differently, and thus leads to different results.
Upvotes: 1
Reputation: 4755
a = 1
b = 2
c = 3
For easier reading, I'll rename the variables in func
to pa
, pb
and pc
. So what you're mixing up in func
makes:
pa
point to what pb
is pointing to (b
)pb
point to what pc
is pointing to (c
)pc
point to what pa
is pointing to (which is now b
)Therefore
*pa = 0
follows pa
's pointer (to b
) and sets that to 0, giving you:
a = 1
b = 0
c = 3
However
*pb = 0
instead follows pb
's pointer (to c
) and sets that to 0, giving you:
a = 1
b = 2
c = 0
Upvotes: 2
Reputation: 67352
when I change *a with *c the answer is same
Why would you expect any different? You wrote c=a;
just above it.
changing with *b=0, the answer is 1 2 0
Indeed, you wrote b=c;
before it, so writing 0
in *b
will zero out the third parameter's contents.
Upvotes: 0