读书人

move函数在把string串移到pchar串时的

发布时间: 2012-04-23 13:17:38 作者: rapoo

move函数在把string串移到pchar串时的小问题,高手进,在线等
myfun(sSrc,sKey:string):string;
var
pKey,pSrc:pchar;
iKey,iSrc:integer
begin
try
iKey:=length(sKey);
GetMem(pKey,iKey);
Move(sKey[1],pKey^,iKey); //这里有问题:如果sKey值为'11111187654321',那么pKey得到的值会比sKey值多,比如
//可能会是‘11111187654321n'或者'1111118765432108'
iSrc:=length(sSrc);
GetMem(pSrc,iSrc);
Move(sSrc[1],pSrc^,iSrc);
finally
freeMem(pKey);
freeMem(pSrc);
end;
end;

为什么?

[解决办法]
iKey:=length(sKey) + 1; //pchar还有个结尾的#0
[解决办法]
delphi什么版本
[解决办法]

Delphi(Pascal) code
delphi7下,没问题var pKey: PChar; sKey: string; iKey: Integer;begin  sKey := '11111187654321';  try    iKey := length(sKey) + 1;    GetMem(pKey, iKey);    Move(sKey[1], pKey^, iKey);    Caption := pKey;  finally    FreeMem(pKey);  end;
[解决办法]
分配控件少了一位,并且结尾处要拷贝一个零。
[解决办法]
参考一下这个
function TStrings.GetTextStr: string;
var
I, L, Size, Count: Integer;
P: PChar;
S, LB: string;
begin
Count := GetCount;
Size := 0;
LB := LineBreak;
for I := 0 to Count - 1 do Inc(Size, Length(Get(I)) + Length(LB));
SetString(Result, nil, Size);
P := Pointer(Result);
for I := 0 to Count - 1 do
begin
S := Get(I);
L := Length(S);
if L <> 0 then
begin
System.Move(Pointer(S)^, P^, L);
Inc(P, L);
end;
L := Length(LB);
if L <> 0 then
begin
System.Move(Pointer(LB)^, P^, L);
Inc(P, L);
end;
end;
end;
[解决办法]
改成Move(sKey[1]^,pKey^,iKey);
[解决办法]
其实2楼已经说了,长度要加1。而且,长度加1后getmem你不给它置0,它是未定义的。象下面肯定没问题:
Delphi(Pascal) code
var pKey: PChar; sKey: string; iKey: Integer;begin  sKey := '11111187654321';  try    iKey := length(sKey) + 1;    GetMem(pKey, iKey);    FillChar(PKey^,iKey,#0);//记得初始化,不然未定义    Move(sKey[1], pKey^, iKey-1);    Caption := pKey;  finally    FreeMem(pKey);  end;
[解决办法]
是GetMem的问题吧,他本身是分配内存不清空的用allocmem替换
另外用length(sKey) + 1确实是好习惯

[解决办法]
StrCopy函数帮助中例子:
var
Buffer: PChar;
begin
GetMem(Buffer,Length(Label1.Caption) + Length(Edit1.Text) + 1);
StrCopy(Buffer, PChar(Label1.Caption));
StrCat(Buffer, PChar(Edit1.Text));
Label1.Caption := Buffer;
Edit1.Clear;
FreeMem(Buffer);
end
[解决办法]
楼主的问题,主要是出在对string、pchar类型的理解上。string类型是个不定长、以#0结尾的数据,我们可以这样测试下:
Delphi(Pascal) code
procedure TForm1.Button1Click(Sender: TObject);var s:string;begin  s:='string是个怎样的数据?';  showmessage(s);  s[7]:=#0;  showmessage(s);end; 

读书人网 >.NET

热点推荐