var
s:string;
ps:Pchar;
b:pbyte;
len:integer;
begin
s:=edit1.Text; //字符串
ps:=pchar(s); //轉成pchar類型,
len:=length(s);//取字符串長度,占用多少字節
getmem(b,len);//申請內存,pchar,pbyte在使用前都必須要申請內存,因為他們是指針.
move(ps^,b^,len);//這里 ps^意思是pchar指向內存數據的第一個字節地址,B^是表示申請內存的第一個字節地址,這樣就可以一個一個字節的移到b里去了.
memo1.Text:=pchar(b);//顯示.
freemem(b);
end;
有些人遇到的困惑是為什么 move(s,b,len)不行呢?同樣我也遇到這樣的困惑.
看了一樣move的函數源碼才明白.
procedure Move( const Source; var Dest; count : Integer );
{$IFDEF PUREPASCAL}
var
S, D: PChar;
I: Integer;
begin
S := PChar(@Source);//取內存地址
D := PChar(@Dest);//取內存地址
if S = D then Exit;
if Cardinal(D) > Cardinal(S) then
for I := count-1 downto 0 do
D[I] := S[I]
else
for I := 0 to count-1 do
D[I] := S[I];
end;
如果直接傳入s,
S := PChar(@Source);//取內存地址\
就相當於取的字符串S地址的地址.
如果傳入的是ps^
S := PChar(@Source);//取內存地址
就相當於取pchar 所指向字符串實際數據的地址.
