这个程序为啥不能对两个整型变量的值进行交换

来源:百度知道 编辑:UC知道 时间:2024/05/29 06:50:54
# include <stdio.h>
main()
{
int *a,*b;
*a=10,*b=20;
swap(a,b);
printf("%d %d\n",*a,*b);
}
swap(p,q)
int *p,*q;
{
int t;
t=*p;*p=*q;*q=t;
}

int *a,*b;
*a=10,*b=20; // 没有给a,b 分配存放单元

----------------
改成:
#include <stdio.h>
void swap(p,q);

void main()
{
int *a,*b;
int c,d;
a = &c; b=&d;
*a=10,*b=20;
swap(a,b);
printf("%d %d\n",*a,*b);
}
void swap(p,q)
int *p,*q;
{
int t;
t=*p;*p=*q;*q=t;
}

*p = *q ; p和q的值都是q的旧值。
q的旧值就丢了