C:指標函數一些誤區

來源:互聯網
上載者:User

標籤:

當我們學完指標,知道每個數在記憶體中都佔有一定的位元組,也就是地址,才有取地址符號&,所以要交換兩個數必須把這兩個數所對應的記憶體互換,比如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:指標函數一些誤區

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.