標籤:
當我們學完指標,知道每個數在記憶體中都佔有一定的位元組,也就是地址,才有取地址符號&,所以要交換兩個數必須把這兩個數所對應的記憶體互換,比如a=2;b=3;要讓它們互換且輸出,我們用一個函數來試試
1 #include "stdio.h" 2 int temp(int x,int y) 3 { 4 int c; 5 c=x; 6 x=y; 7 y=c; 8 } 9 void main()10 {11 int a,b;12 a=2;13 b=3;14 temp(a,b);15 printf("a=%d,b=%d",a,b);16 }
很顯然,這個方法並不行,它只是在表面互換a,b的值,並且函數只有在啟動並執行時候是有記憶體的,當結束時,函數的記憶體便撤掉,讓我們再看一個更讓人誤解的例子:
1 #include "stdio.h" 2 int temp(int x,int y) 3 { 4 int *p,*q,t; 5 p=&x; 6 q=&y; 7 t=*p; 8 *p=*q; 9 *q=t;10 }11 void main()12 {13 int a,b;14 a=2;15 b=3;16 temp(a,b);17 printf("a=%d,b=%d",a,b); 18 }
上面函數用了指標為什麼還是不行?其實跟上一個例子差不多,在主函數main()中調用temp(a,b)作為實參傳遞給int temp(int x,int y)形參期間傳遞的是值2,3;並不是a,b的地址,然後取的是2,3的地址,結果就是2,3的地址互換,然而a=2,b=3還是沒變,接下來看個正確是例子:
1 #include "stdio.h" 2 int temp(int *p,int *q) 3 { 4 int t; 5 t=*p; 6 *p=*q; 7 *q=t; 8 } 9 void main()10 {11 int a,b;12 a=2;13 b=3;14 temp(&a,&b);15 printf("a=%d,b=%d",a,b); 16 }
運行結果:,這時實參是temp(&a,&b);互換a,b的地址。
C:指標函數一些誤區