返回列表 發帖

指標 (三)

本帖最後由 tonyh 於 2014-9-13 17:31 編輯

利用指標法 (變更門牌), 將變數x與變數y的值對調.

  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4. int main()
  5. {
  6.      int x=10, y=5;
  7.      int *xPtr=&x, *yPtr=&y;  //宣告指標xPtr與yPtr,同時將x與y的位址指派給它們
  8.      cout<<"[對調前]"<<endl;
  9.      cout<<"x="<<*xPtr<<endl;
  10.      cout<<"y="<<*yPtr<<endl;
  11.      cout<<"變數x的位址: "<<xPtr<<endl;
  12.      cout<<"變數y的位址: "<<yPtr<<endl<<endl;
  13.      xPtr=&y;
  14.      yPtr=&x;
  15.      cout<<"[對調後]"<<endl;
  16.      cout<<"x="<<*xPtr<<endl;
  17.      cout<<"y="<<*yPtr<<endl;
  18.      cout<<"變數x的位址: "<<xPtr<<endl;
  19.      cout<<"變數y的位址: "<<yPtr<<endl<<endl;
  20.      system("pause");
  21.      return 0;
  22. }
複製代碼
附件: 您需要登錄才可以下載或查看附件。沒有帳號?註冊

返回列表