
- Pascal 教程
- Pascal - 首頁
- Pascal - 概述
- Pascal - 環境設定
- Pascal - 程式結構
- Pascal - 基本語法
- Pascal - 資料型別
- Pascal - 變數型別
- Pascal - 常量
- Pascal - 運算子
- Pascal - 決策
- Pascal - 迴圈
- Pascal - 函式
- Pascal - 過程
- Pascal - 變數作用域
- Pascal - 字串
- Pascal - 布林值
- Pascal - 陣列
- Pascal - 指標
- Pascal - 記錄
- Pascal - 變體
- Pascal - 集合
- Pascal - 檔案處理
- Pascal - 記憶體
- Pascal - 單元
- Pascal - 日期和時間
- Pascal - 物件
- Pascal - 類
- Pascal 有用資源
- Pascal - 快速指南
- Pascal - 有用資源
- Pascal - 討論
Pascal - 指標
Pascal 中的指標易於學習且趣味十足。一些 Pascal 程式設計任務使用指標可以更輕鬆地完成,而其他任務(例如動態記憶體分配)則無法在不使用指標的情況下完成。因此,學習指標成為一名完美的 Pascal 程式設計師就變得很有必要。讓我們以簡單易懂的步驟開始學習它們。
如你所知,每個變數都是一個記憶體位置,每個記憶體位置都有其定義的地址,可以使用指標變數的名稱來訪問該地址,該名稱表示記憶體中的地址。
什麼是指標?
指標是一個動態變數,其值是另一個變數的地址,即記憶體位置的直接地址。與任何變數或常量一樣,在使用指標儲存任何變數地址之前,必須先宣告它。指標變數宣告的一般形式為:
type ptr-identifier = ^base-variable-type;
指標型別透過在基本型別前加上向上箭頭或插入符號(^)來定義。基本型別定義資料項的型別。一旦將指標變數定義為某種型別,它只能指向該型別的資料項。定義指標型別後,我們可以使用 var 宣告來宣告指標變數。
var p1, p2, ... : ptr-identifier;
以下是一些有效的指標宣告:
type Rptr = ^real; Cptr = ^char; Bptr = ^ Boolean; Aptr = ^array[1..5] of real; date-ptr = ^ date; Date = record Day: 1..31; Month: 1..12; Year: 1900..3000; End; var a, b : Rptr; d: date-ptr;
指標變數透過使用相同的插入符號(^)來取消引用。例如,指標 rptr 引用的關聯變數為 rptr^。可以按以下方式訪問它:
rptr^ := 234.56;
以下示例將說明此概念:
program exPointers; var number: integer; iptr: ^integer; begin number := 100; writeln('Number is: ', number); iptr := @number; writeln('iptr points to a value: ', iptr^); iptr^ := 200; writeln('Number is: ', number); writeln('iptr points to a value: ', iptr^); end.
編譯並執行上述程式碼後,將產生以下結果:
Number is: 100 iptr points to a value: 100 Number is: 200 iptr points to a value: 200
在 Pascal 中列印記憶體地址
在 Pascal 中,我們可以使用地址運算子 (@) 將變數的地址賦給指標變數。我們使用此指標來操作和訪問資料項。但是,如果由於某種原因,我們需要處理記憶體地址本身,則需要將其儲存在 word 型別變數中。
讓我們擴充套件上面的示例以列印儲存在指標 iptr 中的記憶體地址:
program exPointers; var number: integer; iptr: ^integer; y: ^word; begin number := 100; writeln('Number is: ', number); iptr := @number; writeln('iptr points to a value: ', iptr^); iptr^ := 200; writeln('Number is: ', number); writeln('iptr points to a value: ', iptr^); y := addr(iptr); writeln(y^); end.
編譯並執行上述程式碼後,將產生以下結果:
Number is: 100 iptr points to a value: 100 Number is: 200 iptr points to a value: 200 45504
空指標
如果您沒有要分配的確切地址,則始終建議將 NIL 值分配給指標變數。這在變數宣告時完成。分配了 NIL 的指標不指向任何地方。考慮以下程式:
program exPointers; var number: integer; iptr: ^integer; y: ^word; begin iptr := nil; y := addr(iptr); writeln('the vaule of iptr is ', y^); end.
編譯並執行上述程式碼後,將產生以下結果:
The value of ptr is 0
要檢查 nil 指標,您可以使用如下所示的 if 語句:
if(ptr <> nill )then (* succeeds if p is not null *) if(ptr = nill)then (* succeeds if p is null *)
Pascal 指標詳解
指標有很多但簡單的概念,它們對 Pascal 程式設計非常重要。以下是一些重要的指標概念,Pascal 程式設計師應該清楚:
序號 | 概念及描述 |
---|---|
1 |
Pascal - 指標運算
指標可以使用四種算術運算子:增量、減量、+、- |
2 |
Pascal - 指標陣列
您可以定義陣列來儲存多個指標。 |
3 |
Pascal - 指向指標的指標
Pascal 允許您對指標進行指標操作,依此類推。 |
4 |
在 Pascal 中將指標傳遞給子程式
按引用或按地址傳遞引數都可以使被呼叫子程式在呼叫子程式中更改傳遞的引數。 |
5 |
在 Pascal 中從子程式返回指標
Pascal 允許子程式返回指標。 |