System ReallocMem (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code demostrates the use of ReallocMem function. Three edit boxes and a button are expected on the form.

Code

function FastStrCat(const S1, S2: String): String;
var
  FinalStr: PChar;
begin
  {
   Allocated enough space in FinalStr to copy the contents
   of the initial string, including the $00 character.
  }
  GetMem(FinalStr, (Length(S1) + 1) * SizeOf(Char));

  { Copy the contents of the first string. }
  MoveChars(S1[1], FinalStr^, Length(S1) + 1);

  { Now expand the final string, including the $00 character. }
  ReallocMem(FinalStr, (Length(S1) + Length(S2) + 1) * SizeOf(Char));

  { Copy the contents of the second string. }
  MoveChars(S2[1], FinalStr[Length(S1)], Length(S2) + 1);

  { Get the result in String. }
  SetString(Result, FinalStr, Length(S1) + Length(S2));
  FreeMem(FinalStr);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  { Concatenate two strings. }
  Edit3.Text := FastStrCat(Edit1.Text, Edit2.Text);
end;

Uses