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;
3 回答
最好的方法是使用数组 . 如果imsize是常量,则需要静态数组,否则,您将使用动态数组 . 以下是两者的语法:
静态的:
动态:
至于灰色,你如何'll declare it depends on if you'使用"unsigned chars"数组作为字符(一个字符串)或单字节整数 . 如果它们是整数,则可以将无符号单字节整数声明为
byte
,并使用上述语法声明它们的数组(静态或动态) . 如果它们是字符,只需使用string
类型 .指针数学是可能的,但不推荐,因为它使缓冲区溢出太容易了 . 相反,尝试将您的其他变量声明为
integer
并将其用作数组的索引 . 如果您打开了边界检查,这将阻止您超出阵列的末尾并破坏内存 .在Delphi中你可以使用指针(比如在C / C中),但通常你会尝试避免它 .
代码看起来最像
那些指出你应该使用数组类型而不是直接指针操作的人,正如你在C中看到的那样,是正确的,当安全数组更容易时,Delphi使用危险的指针类型并不是惯用的,可以验证更快,在运行时更安全 . 然而对于那些想要避免使用内置数组类型的迂腐的人来说,尽管很愚蠢,但这样做是可能的: