2

我在 Delphi 中有一个程序,目前看起来像这样:

Procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
VAR
    i : LongInt;
    Errors : Array[N] of LongInt;
BEGIN

for i := 0 to N-1 do
  Errors[i] := 0;

END;

我得到一个错误,即传递给错误定义的 N 是一个未声明的标识符,尽管在过程定义中声明了它。N 在 BEGIN-END 部分被识别。任何想法是什么导致了这种情况以及我如何在 VAR 部分中声明一个可变长度数组?

4

2 回答 2

11

你写array of Int来声明一个s的动态数组Int

procedure Time.TimeDB(algorithm: string; Encode, Decode: InputFunction; N, R: Int);
var
  i: int;
  errors: array of Int;
begin

  SetLength(errors, N);
  for i := 0 to N - 1 do
    Errors[i] := 0;

end;

还要注意,如果一个数组有N元素,那么它们是索引0的 , 1, ..., N - 1。没有索引的元素N

(另外,你确定你integer写的时候不是这个意思Int吗?)


该构造array[M..N] of Int称为静态数组。在这种情况下,MandN必须是常量,例如array[0..15] of TColor. 您还获得了静态数组声明array[TMyType] of TMySecondType,其中索引的类型TMyType为 ,如array[byte] of TColoror array[TFontStyle] of cardinal

于 2013-08-09T15:25:14.780 回答
1

在您的代码中,您将错误数组初始化为零...注意使用 SetLength 您不需要这样做...只需将数组设置为 0,然后将其设置为您想要的长度,然后只需分配您的值需要。

procedure WorkArrays(var aWorking: array of integer);
begin
  if High(aWorking) >= 0 then
    aWorking[0] := 1;
  if High(aWorking) >= 3 then
    aWorking[3] := 5;
end;

procedure WorkArrays2(var aWorking: array of integer);
begin
  if High(aWorking) >= 1 then
    aWorking[1] := 4;
  if High(aWorking) >= 9 then
    aWorking[9] := 7;
end;

procedure WorkArrays3(var aWorking: TIntArray);
begin
  SetLength(aWorking, 4);
  aWorking[0] := 1;
  aWorking[3] := 5;
end;

procedure WorkArrays4(var aWorking: TIntArray);
begin
  SetLength(aWorking, 10);
  aWorking[1] := 4;
  aWorking[9] := 7;
end;

procedure TForm58.ShowArrays(aWorking: array of integer);
var
  a_Index: integer;
begin
  for a_Index := Low(aWorking) to High(aWorking) do
    Memo1.Lines.Add(IntToStr(aWorking[a_Index]));
end;

procedure TForm58.ShowArrays2(aWorking: TIntArray);
var
  a_Index: integer;
begin
  for a_Index := Low(aWorking) to High(aWorking) do
    Memo1.Lines.Add(IntToStr(aWorking[a_Index]));
end;

procedure TForm58.Button1Click(Sender: TObject);
var
  a_MyArray: array of integer;
  a_MyArray1: TIntArray;
begin
  SetLength(a_MyArray, 3);//note this is a Zero based Array...0 to 2
  WorkArrays(a_MyArray);//note aWorking[3] will not show...because High is 2...
  ShowArrays(a_MyArray);
  SetLength(a_MyArray, 0);
  SetLength(a_MyArray, 10);//note this is a Zero based Array...0 to 9
  WorkArrays2(a_MyArray);
  ShowArrays(a_MyArray);
  WorkArrays3(a_MyArray1);
  ShowArrays2(a_MyArray1);
  WorkArrays4(a_MyArray1);
  ShowArrays2(a_MyArray1);
end;

结尾。

于 2013-08-09T20:21:26.033 回答