字符串与字符数组、字符指针的赋值

unit Unit1;

interface

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

type
  TForm5 = 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 }
    FS: string;
    FA1: array [0..5] of Char;
    FA2: array of Char;
    FP: PChar;
  public
    { Public declarations }
  end;

var
  Form5: TForm5;

implementation

{$R *.dfm}

procedure TForm5.btn1Click(Sender: TObject);
begin
  Caption := Format('FS addr is %d, FP is %d', [Integer(FS), Integer(FP)]);      //相等
end;

procedure TForm5.btn2Click(Sender: TObject);
begin
  StrCopy(@FA1, PChar(FS));   //字符串值给数据需要拷贝;  StrCopy不需要输入长度
  Caption := FA1;             //字符数组可以直接赋值给字符串
end;

procedure TForm5.btn3Click(Sender: TObject);
begin
//  StrCopy(@FA2, PChar(FS));          //异常
//  Caption := PChar(FA2);             //动态数组不能直接赋值给字符串

  StrCopy(PChar(FA2), PChar(FS));     //说明FA2应该是指针
  Caption := PChar(FA2);              //动态数组转化成字符指针之后赋值给字符串
end;

procedure TForm5.FormCreate(Sender: TObject);
begin
  FS := '123456';
  FP := PChar(FS);
  SetLength(FA2, 6);
  Caption := PChar(FS)^;     //FS确实是字符串的首地址
end;

/// <remarks>
///  1:字符串其实是一指针
///  2:数组、字符串指针都可直接赋值给字符串
///  3:字符串赋值给数据需要拷贝
/// </remarks>
///
end.

 

    原文作者:carldada
    原文地址: https://blog.csdn.net/carldada/article/details/86634359
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞