简体   繁体   English

将常量数组复制到 Delphi 中的动态数组

[英]Copy const array to dynamic array in Delphi

I have a fixed constant array我有一个固定的常量数组

constAry1: array [1..10] of byte = (1,2,3,4,5,6,7,8,9,10);

and a dynamic array和一个动态数组

dynAry1: array of byte;

What is the easiest way to copy the values from constAry1 to dynAry1 ?将值从constAry1复制到dynAry1的最简单方法是什么?

Does it change if you have a const array of arrays (multidimensional)?如果您有一个常量数组(多维),它会改变吗?

constArys: array [1..10] of array [1..10] of byte = . . . . .

This will copy constAry1 to dynAry .这会将constAry1复制到dynAry

SetLength(dynAry, Length(constAry1));
Move(constAry1[Low(constAry1)], dynAry[Low(dynAry)], SizeOf(constAry1));
function CopyByteArray(const C: array of Byte): TByteDynArray;
begin
  SetLength(Result, Length(C));
  Move(C[Low(C)], Result[0], Length(C));
end;

procedure TFormMain.Button1Click(Sender: TObject);
const
  C: array[1..10] of Byte = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
var
  D: TByteDynArray;
  I: Integer;
begin
  D := CopyByteArray(C);
  for I := Low(D) to High(D) do
    OutputDebugString(PChar(Format('%d: %d', [I, D[I]])));
end;

procedure TFormMain.Button2Click(Sender: TObject);
const
  C: array[1..10, 1..10] of Byte = (
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
    (1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

var
  D: array of TByteDynArray;
  I, J: Integer;
begin
  SetLength(D, Length(C));
  for I := 0 to Length(D) - 1 do
    D[I] := CopyByteArray(C[Low(C) + I]);

  for I := Low(D) to High(D) do
    for J := Low(D[I]) to High(D[I]) do
      OutputDebugString(PChar(Format('%d[%d]: %d', [I, J, D[I][J]])));
end;

From Delphi XE7, the use of string-like operations with arrays is allowed.从 Delphi XE7 开始,允许对数组使用类似字符串的操作。 Then you can declare a constant of a dynamic array directly.然后你可以直接声明一个动态数组的常量。 For example:例如:

const
  KEY: TBytes = [$97, $45, $3b, $3e, $c8, $14, $c9, $e1];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM