最近复习到这一块再提一句,大一以后就没怎么用过c了
void swap1(int *a,int *b){ int tmp = *a; *a = *b; *b =tmp; } void swap2(int *a,int *b){ int *t = a; a = b; b = t; } int main(int argc, char *argv[]) { int a = 2,b = 8; swap1(&a , &b); cout<<a<<" "<<b<<endl; int *p = &a, *t = &b; swap1(p , t); cout<<a<<" "<<b<<endl; swap2(p,t); cout<<*p<<" "<<*t<<endl; return 0; }
解释一下swap2()为什么没有交换成功。相当于指针变量的值交换,不影响实参。