1 / 11

資料!你家住哪裏?

資料!你家住哪裏?. --談指標 200 8 . 1 2. 綠園. 何謂「 指標 」?. 指標可看成是一種 特殊的變數 ,用來存放變數在記憶體中的 位址 ( address) 。 如果指標 ptr 存放了變數 a 的位址,則我們就說「 指標 ptr 指向變數 a 」。. 變數 a. 為什麼要使用指標. 當函數必須傳回一個以上的值。 使得函數在傳遞陣列或字串資料時更有效率 。 較複雜的資料結構須要用指標來把資料鏈結在一起。 如鏈結串列( linked list) 或二元樹( binary tree) 等。

menora
Download Presentation

資料!你家住哪裏?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 資料!你家住哪裏? --談指標 2008.12. 綠園

  2. 何謂「指標」? • 指標可看成是一種特殊的變數,用來存放變數在記憶體中的位址(address)。 • 如果指標ptr存放了變數a的位址,則我們就說「指標ptr指向變數a」。 變數a

  3. 為什麼要使用指標 • 當函數必須傳回一個以上的值。 • 使得函數在傳遞陣列或字串資料時更有效率。 • 較複雜的資料結構須要用指標來把資料鏈結在一起。如鏈結串列(linked list)或二元樹(binary tree)等。 • 許多函數必須利用指標來傳達記憶體的訊息。如動態記憶體配置、檔案開啟函數及檔案讀寫函數等。

  4. 指標變數 • 指標變數的宣告: int *ptr1; /*可指向整數型態的變數*/ char *ptr2; /*可指向字元型態的變數*/

  5. 指標變數(續) • 指標變數的使用: • 位址運算子 & :用來求取變數的位址。 • 取值運算子 *: 用來取得指標所指向的記憶體位址的內容。 • 範例: int a = 10, b; int *p; p = &a; b = *p; *p = 20; 結果:a = 20, b = 10

  6. 指標變數的運算 int a=10, b=20; int *p1, *p2; char ch=’a’, *pch; /* 設定運算 */ p1 = &a; /* 將a的位址存放於p1 */ p2 = &b; /* 將b的位址存放於p2 */ pch = &ch; /* 將ch的位址存放於pch */ /* 加減法運算 */ p1++; /* 將p1所存整數a位址加上整數型態長度4bytes */ pch--; /* 將pch所存字元ch位址減去字元型態長度1byte */ /* 差值運算*/ sub1 = p1 – p2; /* 計算p1和p2相差距離 */ sub2 = *p1 – *p2; /* 計算p1所指變數a和p2所指變數b的差 */

  7. 牛刀小試(一) • 欲將指標變數 ptr指向整數變數 i,下列何者正確? Ans:_ (a) i = *ptr; (b) ptr = &i; (c) ptr = *i; (d) *ptr = i;

  8. 牛刀小試(一) 欲將指標變數 ptr指向整數變數 i,下列何者正確? Ans:b_ (a) i = *ptr; (b) ptr = &i; (c) ptr = *i; (d) *ptr = i;

  9. 指標與函數 • 在函數中,若是想傳回某個結果給原呼叫函數,可以用return敘述,但是,return 敘述只能傳回一個值!所以,當程式中需要傳遞兩個以上的值,就無法利用 return 敘述。此時,指標就可以解決函數間傳遞多個傳回值的問題。

  10. 指標與函數 【範例1】 /* 將兩數互換 */ void swap(int x, int y) { int temp=x; x=y; y=temp; return; } #include <iostream> #include <cstdlib> using namespace std; void swap(int,int); int main(void) { int a=3,b=5; cout<<"Before swap…\n"; cout<<"a="<<a<<“,b="<<b<<endl; cout<<"After swap…\n"; swap(a, b); cout<<"a="<<a<<“,b="<<b<<endl; system("PAUSE"); return 0; } 執行結果: Before swap… a=3, b=5 After swap… a=3, b=5

  11. 指標與函數 【範例1-1】 /* 將兩數互換 */ void swap(int *x, int *y) { int temp=*x; *x=*y; *y=temp; return; } #include <iostream> #include <cstdlib> using namespace std; void swap(int *,int *); int main(void) { int a=3,b=5;   cout<<"Before swap…\n"; cout<<"a="<<a<<“,b="<<b<<endl; cout<<"After swap…\n"; swap(&a, &b); cout<<"a="<<a<<“,b="<<b<<endl; system("PAUSE"); return 0; } 執行結果: Before swap… a=3, b=5 After swap… a=5, b=3

More Related