读帮助文档发现Delphi2009的新特性,象C语言一样用数组方式使用指针.

来源:互联网 发布:批八字算命软件 编辑:程序博客网 时间:2024/06/05 10:31

 传统的Pascal指针和数组不是等价概念.不能像数组一样使用下标指针(编译器特殊处理的PChar类型除外).

而C语言中数组就是数组第一个元素的地址.和指针在一定程度上等价.指针所指向的内容也可以象数组一样用下标来访问.

虽然问题不大但是写起代码来就麻烦,而且不直观.

如下代码以往的Delphi只能这样写.

const
  rw = 10;
  rh = 10;
procedure SetRects(lpRect: PRect; dwCount : Cardinal);
var
  I : Integer;
begin
  for I := 0 to dwCount - 1 do
  begin
    lpRect^ := Rect(I*rw, 0, I*rw+rw, rh);
    Inc(lpRect);
  end;
end;

或者非要用下标访问的话就要变通一下.

const
  rw = 10;
  rh = 10;
procedure SetRects(lpRect: PRect; dwCount : Cardinal);
type
  TRects = array[0..0]of TRect;
  pRects = ^TRects;
var
  I : Integer;
  lpRects : pRects;
begin
  lpRects := pRects(lpRect);
  for I := 0 to dwCount - 1 do
  begin
    lpRects[I] := Rect(I*rw, 0, I*rw+rw, rh);
  end;
end;

但是Delphi2009新增了编译开关,允许象C语言一样用下标直接访问数组所指向的元素.

{$POINTERMATH ON}
const
  rw = 10;
  rh = 10;
procedure SetRects(lpRect: PRect; dwCount : Cardinal);
var
  I : Integer;
begin
  for I := 0 to dwCount - 1 do
  begin
    lpRect[I] := Rect(I*rw, 0, I*rw+rw, rh);
  end;
end;

呵呵方便多了.

不过要注意默认是{$POINTERMATH  OFF}的.

 

原创粉丝点击