- 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 允许子程序返回指针。 |