标签:blog http io ar for 2014 on log amp
相信下面這個C程序很多人都見過啦,當時自己看 美少女战士谭浩强 写的那本书上的解释,反正我当时是没看太懂具体是什么意思,谱架啊~~~
#include <stdio.h> void swap(int x, int y) { int temp = x; x = y; y = temp; } int main() { int n, m; while(~scanf("%d %d", &n, &m)) { swap(n, m); printf("%d <--> %d\n", n, m); } return 0; }
#include <stdio.h> void swap(int x, int y) { printf("The formal parameter X's address : %d\n", &x); printf("The formal parameter Y's address : %d\n", &y); printf("--------------------------------------------\n"); int temp = x; x = y; y = temp; printf("The formal parameter X's address : %d\n", &x); printf("The formal parameter Y's address : %d\n", &y); printf("--------------------------------------------\n"); } int main() { int n, m; while(~scanf("%d %d", &n, &m)) { printf("The actual parameter N's address : %d\n", &n); //呢个actual 同埋formal系实参,形参唧意思; printf("The actual parameter M's address : %d\n", &m); printf("--------------------------------------------\n"); swap(n, m); printf("%d <--> %d\n", n, m); } return 0; }
从运行结果可以看到实参与形参的地址是不一样滴,所以,你改变形参内存地址存储的值不会影响到实参内存地址中存储的值; 实参与形参的结合只是值传递,而不是地址传递;
所以从这个“实参向形参传递地址”这个思路当中可以实现swap函数的功能:
#include <stdio.h> void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } int main() { int n, m; while(~scanf("%d %d", &n, &m)) { swap(&n, &m); //传递的是地址,所以形參與实参对应共用同一段地址; printf("%d <--> %d\n", n, m); } return 0; }
#include <stdio.h> void swap(int &x, int &y) { int temp = x; x = y; y = temp; } int main() { int n, m; while(~scanf("%d %d", &n, &m)) { swap(n, m); printf("%d <--> %d\n", n, m); } return 0; }
悄悄告訴你,還有一種方法啦,哈哈:
#include <stdio.h> int swap(int &a, int &b) { a = a ^ b; b = a ^ b; a = a ^ b; } int main() { int n, m; while(~scanf("%d %d", &n, &m)) { swap(n, m); printf("%d <--> %d\n", n, m); } return 0; }
标签:blog http io ar for 2014 on log amp
原文地址:http://blog.csdn.net/keshacookie/article/details/40213495