Delphi中的动态数组和指针

Kow*_*kus 2 delphi

如何在Delphi中重写这个C++代码?

int *intim = new int[imsize];
unsigned char *grays = new unsigned char[imsize];
int *intim2 = intim;
Run Code Online (Sandbox Code Playgroud)

我怎样才能像这样增加指针:

*(intim++) = x;
Run Code Online (Sandbox Code Playgroud)

Rit*_*tra 7

在Delphi中你可以使用指针(比如在C/C++中),但通常你会尝试避免它.

代码看起来最像

uses
  Types;

procedure Test();
var
  intim: TIntegerDynArray;
  grays: TByteDynArray;
  P:     PInteger;
  i, s:  Integer;
begin
  // 'allocate' the array
  SetLength(intim, imsize);
  SetLength(grays, imsize);

  // if you want to walk through the array (Delphi style)
  for i := Low(intim) to High(intim) do intim[i] := GetValueFromFunction();
  // or (read only access, sum the array)
  s := 0;
  for i in intim do Inc( s, i );
  // or with pointers:
  P := @intim[ 0 ];
  for i := 0 to High(intim) do begin
    P^ := x;
    Inc( P ); // like P++;
  end;
end; 
Run Code Online (Sandbox Code Playgroud)

  • 你应该使用:=低(xxx)到高(xxx)而不是使用:=低(xxx)到高(xxx)如果你习惯了这个,如果你突然遇到定义为[10]的数组,你将不会遇到麻烦..20]的整数.所以 - 习惯使用低价和高价 - 它最终会得到回报...... (6认同)