[英]void pointer swap function in C
i wrote a func swap_pointers meant to replace the memory adresses both pointers point to.我写了一个 func swap_pointers 旨在替换两个指针指向的内存地址。
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
.意思是如果在调用 swap 之前,
v_a
指向int a
, v_b
指向b
,之后v_a
应该指向b
, v_b
a
。
Running main()
, I do see the adresses switch, and callng printf()
indeed prints 6 8
, but when the lines运行
main()
,我确实看到了地址开关,并且 callng printf()
确实打印了6 8
,但是当行
a = *((int *) v_a);
b = *((int *) v_b);
are executed, both vars ( a
and b
) recieve the value 6
.执行后,变量(
a
和b
)都收到值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);
}
After you do the swap, v_a
is pointing to the address of b
, and v_b
is pointing to the address of a
.你做的交换之后,
v_a
指向的地址b
,和v_b
指向的地址a
。
Then, when you do:然后,当你这样做时:
a = *((int *) v_a);
you are actually assigning the value of b
to a
which makes it 6.您实际上是将
b
的值分配给a
,使其为 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.然后,当然,当你分配给
b
的下一行,您要分配的新值a
,这是6。
After calling the function swap_pointers
调用函数
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.指针 v_a 指向变量 b,指针 v_b 指向变量 a。
After this statement在此声明之后
a = *((int *) v_a);
the variable a
has the value 6
.变量
a
的值为6
。 The pointer v_b
points to the variable a
that at this time contains the value 6
.. So after this statement指针
v_b
指向变量a
,此时包含值6
.. 所以在这个语句之后
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
.变量
b
将获取存储在前面赋值语句中获得的变量a
中的值,该值与值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
.要交换变量
a
和b
的值,您需要使用一个中间变量或编写另一个函数来交换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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.