新手教学-指针数据交换
同学们可以运行一下程序,结合指针的概念思考一下结果为何不同程序代码:
#include <stdio.h> void changevalue(int *,int *);/*交换值*/ void changeaddress(int *,int *);/*交换地址*/ int main(void) { int *p,*q,a=1,b=2; p=&a;q=&b; printf("before changed: *p=%d,*q=%d,&p=%d,&q=%d",*p,*q,p,q); printf("\nchange value:\n"); changevalue(p,q); printf("\nafter changed: *p=%d,*q=%d,&p=%d,&q=%d",*p,*q,p,q); a=1;b=2;/*重置a,b,p,q的值*/ p=&a;q=&b; printf("\n\nbefore changed: *p=%d,*q=%d,&p=%d,&q=%d",*p,*q,p,q); printf("\nchange address:\n"); changeaddress(p,q); printf("\n\nbefore changed: *p=%d,*q=%d,&p=%d,&q=%d",*p,*q,p,q); return 0; } void changevalue(int *x, int *y) { int z; z=*x;*x=*y;*y=z; printf("inside(changevalue): x=%d,y=%d,&x=%d,&y=%d",*x,*y,x,y); } void changeaddress(int *x, int *y) { int *z; z=x;x=y;y=z; printf("inside(changeaddress): x=%d,y=%d,&x=%d,&y=%d",*x,*y,x,y); }