二维数组

SetLength(Arr,J,N)

上式为二维数组分配空间,二维数组即是在第一维的元素J上,每个J元素里面再有N个元素。

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  I,J:Integer;
  //ARR1: array [3,5]of string;//報錯![Error]: '..' expected but ',' found
  //ARR1: array [3][5]of string;//報錯![Error]: '..' expected but ',' found
  //下面這2種定義二維數組的方式都是可以的哦:
  //ARR1: array [0..2] of array [0..4] of string;
  ARR1: array[0..2,0..4]of string;
begin
  //Randomize ;
  Memo1.Clear ;
  for I:=0 to 2 do //第一維
  begin
    for J:=0 to 4 do //第二維
    begin
     // ARR1[I,J]:=Random(50);
      ARR1[I,J]:='I='+INTTOSTR(I)+';J='+IntToStr(J);
       Memo1.Lines.Add(ARR1[I,J]);
    end;

  end;
  Memo1.Lines.Add('總數:'+IntToStr(Memo1.Lines.Count));//15
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  i,j:Integer;
  //Arr: array of array of string;  //定義多維數組
  //arr1:array of Integer; //定義一維數組
  Arr:array of array of Integer; //定義多維數組
begin
  {SetLength(Arr,3,5);  //為多維數組分配空間,第一維3個元素,第二維5個元素
  Arr[0,3] := 100;     //賦值
  ShowMessage(IntToStr(Arr[0,3]));  //取值
  }
  //SetLength(Arr1,5);
  Memo1.Clear;
  SetLength(Arr,5); //二維數組初始化,里層先設置再到外層;一來就定義了一個二維數組,所以這個是先給裡面的二維數組初始化分配空間。

  {SetLength(Arr[0],2);
  SetLength(Arr[1],3);
  SetLength(Arr[2],4);
  SetLength(Arr[3],4);
  SetLength(Arr[4],4);}
  for i:=0 to 4 do
  case i  of
    0:
      begin
        SetLength(Arr[i],2);
        for j:=0 to 1 do
        begin
          ARR[I,J]:='I='+INTTOSTR(I)+';J='+IntToStr(J);
          Memo1.Lines.Add(ARR[i,j]);
        end;
      end;
    1:
      begin
        SetLength(Arr[i],3);
        for j:=0 to 2 do
        begin
          ARR[I,J]:='I='+INTTOSTR(I)+';J='+IntToStr(J);
          Memo1.Lines.Add(ARR[i,j]);
        end;
      end;
    2:
      begin
        SetLength(Arr[i],4);
        for j:=0 to 3 do
        begin
          ARR[I,J]:='I='+INTTOSTR(I)+';J='+IntToStr(J);
          Memo1.Lines.Add(ARR[i,j]);
        end;
      end;
    3:
      begin
        SetLength(Arr[i],4) ;
       for j:=0 to 3 do
        begin
          ARR[I,J]:='I='+INTTOSTR(I)+';J='+IntToStr(J);
          Memo1.Lines.Add(ARR[i,j]);
        end;
      end;
    4:
      begin
        SetLength(Arr[i],4);
        for j:=0 to 3 do
        begin
          ARR[I,J]:='I='+INTTOSTR(I)+';J='+IntToStr(J);
          Memo1.Lines.Add(ARR[i,j]);
        end;
      end;
  end;


end;

end.
原文地址:https://www.cnblogs.com/168-h/p/15243580.html