Reputation: 17
#include<Stdio.h>
int main()
{
int a ,b;
int *p;
int *q;
printf("enter the value of a and b");
scanf("%d%d",&a,&b);
p = &a;
q = &b;
printf("value of a and b is %d and %d",a,b);
a = *q;
b = *p;
printf("value of a and b is %d and %d",a,b);
}
i am not able to change value of b, even after redefining it to pointer p.
Upvotes: 0
Views: 59
Reputation: 117298
You are in fact assigning a value to b
, but since you've changed the value of a
, you will not notice the assignment, Let's say you enter 4
for a
and 5
for b
:
a = *q; // q points at b, which is 5, so a = 5
b = *p; // p points at a, which is now 5, so, b = 5
To swap the values, you could instead do:
int tmp = a; // store the value of a, 4
a = b; // assign, a = 5
b = tmp; // assign, b = 4 (the stored value)
or make a function out of it:
void swap(int *lhs, int *rhs) {
int tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
and call it:
swap(&a, &b);
Upvotes: 3