数组拷贝,静态数组并非是指针

unit Unit1;

interface

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

type
  TMyArray = array [0..5] of Integer;

  TForm1 = class(TForm)
    btn1: TButton;
    btn2: TButton;
    btn3: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
    procedure btn3Click(Sender: TObject);
  private
    { Private declarations }
    FA1: array [0..5] of Integer;
    FA2: array of Integer;
    FB1: TMyArray;
    FB2: TMyArray;
    //procedure CopyArray(ASrc: array of Integer; ADes: array of Integer);  //无法拷贝
    //procedure CopyMyArray(ASrc: TMyArray; ADes: TMyArray);                //无法拷贝
    //源数组要声明为const(安全), 目标数组要声明为out
    //开放数组是指数组元素个数不定的数组,并非是变量类型,而是一种参数类型
    procedure CopyArray(const ASrc: array of Integer; out ADes: array of Integer);       //1:开放数组调用
    procedure CopyMyArray(const ASrc: TMyArray; out ADes: TMyArray);                     //2:自定义类型调用
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
procedure TForm1.CopyArray(const ASrc: array of Integer; out ADes: array of Integer);
var
  size: Integer;
begin
  size := SizeOf(ADes);
  CopyMemory(@ADes, @ASrc, size);
end;

procedure TForm1.CopyMyArray(const ASrc: TMyArray; out ADes: TMyArray);
var
  size: Integer;
begin
  size := SizeOf(ADes);
  CopyMemory(@ADes, @ASrc, size);
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  CopyArray(FA1 , FA2);
  Caption := IntToStr(FA2[5]);
end;

procedure TForm1.btn2Click(Sender: TObject);
begin
  CopyMyArray(FB1 , FB2);
  Caption := IntToStr(FB2[5]);
end;

procedure TForm1.btn3Click(Sender: TObject);
begin
  if (@FA1) = (@FA1[0]) then       //两种方法都可以获取数据的地址
    ShowMessage(Format('Address is Equal %d', [Integer(@FA1)]));
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  I: Integer;
begin
  SetLength(FA2, 6);
  for I := 0 to Length(FA1) - 1 do
  begin
    FA1[I] := I;
    FB1[I] := I;
  end;
end;


/// <remarks>
///  1:数组变量表示数组本身,不是数组的地址,这点和C语言差别很大。要获取数组地址用@FArray 或者 @FArray[0];
/// </remarks>
end.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值