对于是值传递还是地址传递不能通过行参来判断,当形参是指针时既有可能是值传递也有可能是地址传递,要画图分析,几个例子如下
- void Exchg1(int x, int y)
- {
- int tmp;
- tmp=x;
- x=y;
- y=tmp;
- }
- void main()
- {
- int a=4,b=6;
- Exchg1 (a,b) ;
- printf("a=%d,b=%d\n",a,b);//4,6
- }
- void Exchg2(int *px, int *py)
- {
- int tmp=*px;
- *px=*py;
- *py=tmp;
- }
- void main()
- {
- int a=4;
- int b=6;
- Exchg2(&a,&b);
- printf("a=%d,b=%d\n", a, b);//6,4
- }
- void Exchg2(int &x, int &y)
- {
- int tmp=x;
- x=y;
- y=tmp;
- }
- void main()
- {
- int a=4;
- int b=6;
- Exchg2(a,b);
- printf("a=%d,b=%d\n", a, b);//6,4
- }
- void swap(int *a,int *b)
- {
- int *tmp=NULL;
- tmp=a;
- a=b;
- b=tmp;
- }
- int main(int argc,char **argv)
- {
- int a=2;
- int b=3;
- printf("Before swap a=%d b=%d\n",a,b);
- swap(&a,&b);
- printf("After swap a=%d b=%d\n",a,b); //2,3
- return 0;
- }
- void swap(int **a,int **b)
- {
- int temp = **a;
- **a = **b;
- **b = temp;
- }
- int main()
- {
- int i = 1;
- int j = 2;
- int *p1 = &i;
- int *p2 = &j;
- int *a = p1;
- int *b = p2;
- swap(&a,&b);
- printf("a = %d,b = %d\n",i,j);//2,1
- return 0;
- }