目录

Pascal - 指针算术( Pointer arithmetic)

正如在主要章节中所解释的,Pascal指针是一个地址,它是存储在单词中的数值。 因此,您可以像对数值一样对指针执行算术运算。 有四个算术运算符可用于指针:递增,递减,+和 - 。

为了理解指针运算,让我们考虑ptr是一个整数指针,它指向地址1000.假设32位整数,让我们对指针执行递增操作 -

Inc(ptr);

现在,在上述操作之后, ptr将指向位置1004,因为每次ptr递增时,它将指向下一个整数位置,其是当前位置旁边的4个字节。 此操作将指针移动到下一个存储器位置,而不会影响存储器位置的实际值。 如果ptr指向其地址为1000的字符,则上述操作将指向位置1001,因为下一个字符将在1001处可用。

增加指针

我们更喜欢在程序中使用指针而不是数组,因为变量指针可以递增,与数组名称不同,因为它是一个常量指针,所以不能递增。 以下程序增加变量指针以访问数组的每个后续元素 -

program exPointers;
const MAX = 3;
var
   arr: array [1..MAX] of integer = (10, 100, 200);
   i: integer;
   iptr: ^integer;
   y: ^word;
begin
   (* let us have array address in pointer *)
   iptr := @arr[1];
   for  i := 1 to MAX do
   begin
      y:= addr(iptr);
      writeln('Address of arr[', i, '] = ' , y^ );
      writeln(' Value of arr[', i, '] = ' , iptr^ );
      (* move to the next location *)
      inc(iptr);
   end;
end.

编译并执行上述代码时,会产生以下结果 -

Address of arr[1] = 13248
 Value of arr[1] = 10
Address of arr[2] = 13250
 Value of arr[2] = 100
Address of arr[3] = 13252
 Value of arr[3] = 200

减少指针

同样的注意事项适用于递减指针,该指针将其值减少其数据类型的字节数,如下所示 -

program exPointers;
const MAX = 3;
var
   arr: array [1..MAX] of integer = (10, 100, 200);
   i: integer;
   iptr: ^integer;
   y: ^word;
begin
   (* let us have array address in pointer *)
   iptr := @arr[MAX];
   for  i := MAX downto 1 do
   begin
      y:= addr(iptr);
      writeln('Address of arr[', i, '] = ' , y^ );
      writeln(' Value of arr[', i, '] = ' , iptr^ );
      (* move to the next location *)
      dec(iptr);
   end;
end.

编译并执行上述代码时,会产生以下结果 -

Address of arr[3] = 13252
 Value of arr[3] = 200
Address of arr[2] = 13250
 Value of arr[2] = 100
Address of arr[1] = 13248
 Value of arr[1] = 10

指针比较

可以使用关系运算符比较指针,例如=,。 如果p1和p2指向彼此相关的变量,例如同一数组的元素,则可以有意义地比较p1和p2。

以下程序通过递增变量指针来修改前一个示例,只要它指向的地址小于或等于数组的最后一个元素的地址,即@arr [MAX] -

program exPointers;
const MAX = 3;
var
   arr: array [1..MAX] of integer = (10, 100, 200);
   i: integer;
   iptr: ^integer;
   y: ^word;
begin
   i:=1;
   (* let us have array address in pointer *)
   iptr := @arr[1];
   while (iptr <= @arr[MAX]) do
   begin
      y:= addr(iptr);
      writeln('Address of arr[', i, '] = ' , y^ );
      writeln(' Value of arr[', i, '] = ' , iptr^ );
      (* move to the next location *)
      inc(iptr);
      i := i+1;
   end;
end.

编译并执行上述代码时,会产生以下结果 -

Address of arr[1] = 13248
 Value of arr[1] = 10
Address of arr[2] = 13250
 Value of arr[2] = 100
Address of arr[3] = 13252
 Value of arr[3] = 200
↑回到顶部↑
WIKI教程 @2018