var
  aa:array of string;
begin
  getmem(aa,3);
  aa[0]:='abcefg';
  aa[1]:='adfs';
  aa[2]:='adfsa';  //为何这里会报错,访问内存地址错误
  freemem(aa);
end;如何用getmem对arry of string类型变量分配内存空间?
还请高手指点,谢谢!

解决方案 »

  1.   

    为何不可以用getmem来分配内存呢?
      

  2.   

    string的结构比较特殊,delphi会对其自动进行管理,通过引用计数来完成。
    它实际还占用地址的低4和低8字节。
      

  3.   

    var
      str: array of String;
    begin
      GetMem( POinter(str),3 * sizeof(String));
      str[2] := '22342342342423';
      Showmessage(str[2]);
      FreeMem(Pointer(str));end;
      

  4.   

    unsigned大哥,我试了您写的代码,同样报错呀!
      

  5.   

    看源代码,学着它的来分配
    function _NewAnsiString(length: Longint): Pointer;
    var
      P: PStrRec;
    begin
      Result := nil;
      if length <= 0 then Exit;
      // Alloc an extra null for strings with even length.  This has no actual cost
      // since the allocator will round up the request to an even size anyway.
      // All widestring allocations have even length, and need a double null terminator.
      GetMem(P, length + sizeof(StrRec) + 1 + ((length + 1) and 1));
      Result := Pointer(Integer(P) + sizeof(StrRec));
      P.length := length;
      P.refcnt := 1;
      PWideChar(Result)[length div 2] := #0;  // length guaranteed >= 2
    end;
      

  6.   

    SetLength(aa,3);
    能够对aa中的元素申请空间,所以,这时aa[0],aa[1],aa[2]3个指针都已经申请了地址空间。

    GetMem(Pointer(aa),3*sizeof(string));只是把aa指针申请了3个空间,指针中的aa[0],aa[1],aa[2]都没有申请空间。所以调用aa[1]等会出错。如果非要用GetMem,试下这样(何必自找麻烦呢):var
      aa:array of string;
    begin
      getmem(Pointer(aa),3*sizeof(string));  getmem(Pointer(aa[0]),sizeof(string));
      getmem(Pointer(aa[1]),sizeof(string));
      getmem(Pointer(aa[2]),sizeof(string));  aa[0]:='abcefg';
      aa[1]:='adfs';
      aa[2]:='adfsa'; 
      freemem(aa);
      

  7.   

    抱歉,没有注意,Array of String不可以这样子使用,我把它当Array of PString了.
      

  8.   

    十分感谢楼上几位大侠指点!想再请教一下gzmhero大侠,为何要用getmem(pointer(aa),3*sizeof(string))的形式对aa申请空间呢?
    为何不可以直接用getmem(aa,3*sizeof(string))申请空间?还是有些不明白,不知大侠是否能再指点一下,谢谢!
      

  9.   

    动态数组,使用 SetLength() 改变其元素数量。