指针传值的小困惑
/* swap3.c -- using pointers to make swapping work */
#include <stdio.h>
void interchange1(int * u, int * v);
int main(void)
{
int x = 5, y = 10;
printf("Originally x = %d and y = %d.\n", x, y);
interchange1(&x, &y); /* send addresses to function */
printf("Now x = %d and y = %d.\n", x, y);
return 0;
}
void interchange(int * u, int * v)
{
int temp;
temp = *u; /* temp gets value that u points to */
*u = *v;
*v = temp;
}
void interchange1(int * u, int * v) //直接交换u和v不就可以吗?
{
int *temp=NULL;
*temp = u; /* temp gets value that u points to */
u = v;
v = *temp;
}指针传值改写形参的两个值,为什么不能直接交换指针变量那?他们存储的都是变量的地址,
交换了地址不就可以吗?运行程序死掉?求解?
temp = u;这还是改变不了x和y的值,因为这样只是改变了u和v两个指针所指的地址,而x和y的值没有变化。
u = v;
v = temp