RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
SysUtils.StrNew Function

Allocates space on and copies a string to the heap; returning a pointer to the string.

Pascal
function StrNew(const Str: PAnsiChar): PAnsiChar; overload;
function StrNew(const Str: PWideChar): PWideChar; overload;
C++
PAnsiChar StrNew(const PAnsiChar Str);
PWideChar StrNew(const PWideChar Str);

StrNew allocates a copy of Str on the heap.  

If Str is nil (Delphi) or NULL (C++) or points to an empty string, StrNew returns a pointer to a new empty string. 

Otherwise, StrNew makes a duplicate of Str, obtaining space with a call to StrAlloc, and returns a pointer to the duplicated string.  

The allocated space is the length of Str + 5 bytes.  

C++ Examples: 

 

/*
This example uses an edit control and a button on a form.
When the button is clicked, memory is allocated for a copy
of the text in the edit control, the text is displayed in a
message box, and then the memory is deallocated.
*/
void __fastcall TForm1::Button1Click(TObject *Sender)
{
  // Allocate memory.
  char* psz = StrNew(Edit1->Text.t_str());
  Application->MessageBox(
    Edit1->Text.c_str(),
    L"StrNew, StrDispose example",
    MB_OK);
  // Deallocate memory.
  StrDispose(psz);
}

 

Delphi Examples: 

{
This example uses an edit control and a button on a form.
When the button is clicked, memory is allocated for a copy
of the text in the edit control, the text is displayed in a
message box, and then the memory is deallocated.
}
procedure TForm1.Button1Click(Sender: TObject);
var
  Temp: PChar;
begin
  // Allocate memory.
  Temp := StrNew(PChar(Edit1.Text));
  Application.MessageBox(Temp, 'StrNew, StrDispose example', MB_OK);
  // Deallocate memory.
  SysUtils.StrDispose(Temp);
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!