Pascal - 指针运算



如主要章节所述,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
pascal_pointers.htm
广告

© . All rights reserved.