加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 为什么System.SetLength(Str,Len)会导致Str的地址发生

发布时间:2020-12-15 09:50:18 所属栏目:大数据 来源:网络整理
导读:代码图 procedure TForm1.FormCreate(Sender: TObject);var Str: string; PStr: PChar;begin Str := 'This a string.'; PStr := Pointer(Str); // PStr holds the address of the first char of Str ShowMessage(IntToStr(Longint(PStr))); // It displays e
代码图

procedure TForm1.FormCreate(Sender: TObject);
var
  Str: string;
  PStr: PChar;
begin
  Str := 'This a string.';
  PStr := Pointer(Str); // PStr holds the address of the first char of Str
  ShowMessage(IntToStr(Longint(PStr))); // It displays e.g. 4928304

  Setlength(Str,20);

  // I don't know what actually happens in the call for SetLength() above,// because the address of Str changes now,so the PStr not valid anymore.

  // This is a proof of the fact
  PStr := Pointer(Str);
  ShowMessage(IntToStr(Longint(PStr))); // It's now different,e.g. 11423804
end;

>为什么System.SetLength(Str,Len)会导致Str的地址发生变化?
>有没有办法使SetLength的副作用无效,这样我就不必将Str的新地址重新分配给PStr了?

解决方法

正如 help on System.SetLength所说“在调用SetLength之后,S保证引用一个唯一的字符串或数组 – 即引用计数为1的字符串或数组.如果没有足够的可用内存来重新分配变量,则SetLength引发一个EOutOfMemory例外.“

它总是重新分配字符串,这就是地址变化的原因.它也是一种获取其他任何东西都不使用的字符串的方法.

更新:为了完全正确,最好重新改写上面的陈述“假设它总是重新分配刺痛更安全”.请参阅以下评论以获得解释.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读