温馨提示×

delphi二维数组怎么定义和赋值

小亿
185
2023-12-01 18:28:34
栏目: 编程语言

在Delphi中,可以使用类似于其他语言的二维数组的概念来定义和赋值二维数组。以下是一个示例:

  1. 定义二维数组:
var
  myArray: array of array of Integer;
  1. 分配二维数组的大小:
SetLength(myArray, rowCount, colCount);

其中,rowCountcolCount分别表示二维数组的行数和列数。

  1. 赋值二维数组的元素:
myArray[rowIndex, colIndex] := value;

其中,rowIndexcolIndex表示要赋值的元素的行索引和列索引,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列的二维数组,并使用嵌套循环对其进行赋值,并最后输出二维数组的内容。输出结果为:

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

0