Reputation: 21
i wrote a func swap_pointers meant to replace the memory adresses both pointers point to.
meaning if before calling swap, v_a
points to the int a
and v_b
to b
, afterwards v_a
should point at b
, and v_b
at a
.
Running main()
, I do see the adresses switch, and callng printf()
indeed prints 6 8
, but when the lines
a = *((int *) v_a);
b = *((int *) v_b);
are executed, both vars (a
and b
) recieve the value 6
.
I can't understand why this is happening.
void swap_pointers(void **a, void **b){
void * tmp=*a;
*a = *b;
*b = tmp;
}
int main() {
int a = 8;
int b = 6;
void *v_a = &a;
void *v_b = &b;
swap_pointers(&v_a, &v_b);
printf("%d %d\n", *((int *) v_a), *((int *) v_b));
a = *((int *) v_a);
b = *((int *) v_b);
}
Upvotes: 1
Views: 724
Reputation: 310980
After calling the function swap_pointers
swap_pointers(&v_a, &v_b);
the pointer v_a points to the variable b amd the pointer v_b points to the variable a.
After this statement
a = *((int *) v_a);
the variable a
has the value 6
. The pointer v_b
points to the variable a
that at this time contains the value 6
.. So after this statement
b = *((int *) v_b);
the variable b
will get the value stored in the variable a
obtained in the precedent assignment statement that is the same value 6
.
To swap the values in the variables a
and b
you need to use an intermediate variable or to write one more function that swaps values in objects of the type int
.
For example
void swap_integers( int *a, int *b )
{
int tmp = *a;
*a = *b;
*b = tmp;
}
The function can be called like
swap_integers( v_a, v_b );
Upvotes: 3
Reputation: 60228
After you do the swap, v_a
is pointing to the address of b
, and v_b
is pointing to the address of a
.
Then, when you do:
a = *((int *) v_a);
you are actually assigning the value of b
to a
which makes it 6.
Then of course, when you do the assignment to b
on the next line, you are assigning the new value of a
, which is 6.
Upvotes: 4