配列の定義と要素への値の代入方法は Delphi の 2 次元配列でどのように行われますか?

Delphiでは,他の言語同様の概念を使って二次元配列を定義、代入できます。以下に例を示します。

  1. 二次元配列を定義する:
var
  myArray: array of array of Integer;
  1. 2次元配列のサイズを割り当てる
SetLength(myArray, rowCount, colCount);

なお、rowCountとcolCountには二次元配列の行数と列数を指定します。

  1. 2 次元配列の要素を代入する:
myArray[rowIndex, colIndex] := value;

rowIndex と colIndex で指定する要素の行インデックスと列インデックス、value でその要素に設定する値を表します。

完全なサンプルコードを以下に示します。

program TwoDimensionalArray;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

var
  myArray: array of array of Integer;
  rowCount, colCount: Integer;
  rowIndex, colIndex: Integer;

begin
  rowCount := 3;
  colCount := 4;
  
  SetLength(myArray, rowCount, colCount);
  
  for rowIndex := 0 to rowCount - 1 do
  begin
    for colIndex := 0 to colCount - 1 do
    begin
      myArray[rowIndex, colIndex] := rowIndex * colCount + colIndex;
    end;
  end;
  
  for rowIndex := 0 to rowCount - 1 do
  begin
    for colIndex := 0 to colCount - 1 do
    begin
      Write(myArray[rowIndex, colIndex], ' ');
    end;
    Writeln;
  end;
  
  Readln;
end.

上記のサンプルコードでは、3行4列の2次元配列を定義し、2重ループで値を代入し、最後に出力しています。出力結果は以下の通りです。

0 1 2 3
4 5 6 7
8 9 10 11
bannerAds