C语言三种参数传递方式
值传递、指针传递、引用传递
只有在函数调用时,才会为形参分配内存空间,调用结束便会释放。
值传递和指针传递,传递的都是实参的一份拷贝。
C语言在线编译器:http://www.dooccn.com/c/
值传递:
#include <stdio.h> void exchange(int x, int y) { int tmp; tmp = x; x = y; y = tmp; printf("x=%d,&x=%d\ny=%d,&y=%d\n",x,&x,y,&y); } int main(void) { int a=3, b=4; printf("a=%d,&a=%d\nb=%d,&b=%d\n",a,&a,b,&b); exchange(a,b); printf("a=%d,&a=%d\nb=%d,&b=%d\n",a,&a,b,&b); return 0; }
结果:
a=3,&a=17295016 b=4,&b=17295020 x=4,&x=17294972 y=3,&y=17294968 a=3,&a=17295016 b=4,&b=17295020
地址传递:
#include <stdio.h> void exchange(int *x, int *y) { int *tmp=NULL; tmp = x; x = y; y = tmp; printf("*x=%d, x=%d\n", *x, x); printf("*y=%d, y=%d\n", *y, y); } int main(void) { int a=3, b=4; printf("a=%d, &a=%d\n", a, &a); printf("b=%d, &b=%d\n", b, &b); exchange(&a,&b); printf("a=%d, &a=%d\n", a, &a); printf("b=%d, &b=%d\n", b, &b); return 0; }
结果:
a=3, &a=-892176920 b=4, &b=-892176916 *x=4, x=-892176916 *y=3, y=-892176920 a=3, &a=-892176920 b=4, &b=-892176916
引用传递
#include <stdio.h> void exchange(int &x, int &y) { int tmp; tmp = x; x = y; y = tmp; printf("x=%d, &x=0x%d\n", x, &x); printf("y=%d, &y=0x%d\n", y, &y); } int main(void) { int a=3, b=4; printf("a=%d, &a=0x%d\n", a, &a); printf("b=%d, &b=0x%d\n", b, &b); exchange(a,b); printf("a=%d, &a=0x%d\n", a, &a); printf("b=%d, &b=0x%d\n", b, &b); return 0; }
结果:
a=3, &a=0x1079344872 b=4, &b=0x1079344876 x=4, &x=0x1079344872 y=3, &y=0x1079344876 a=4, &a=0x1079344872 b=3, &b=0x1079344876