type
TRec = record
  Line1: Integer;
  Line2: Integer;
end;
PRec = ^TRec;
//两种方法
...
function GetRec: PRec;
begin
  Result := nil;
  if True then
  New(PRec);//要不要呢,我是认为应该要,但是如果要,由谁去释放?
    Result.Line1 = 1;
    Result.Line2 = 2;
  end;
end;function GetRec: TRec;
begin
  //Result := nil;这样我就无法返回空值了
  if True then
    Result.Line1 = 1;
    Result.Line2 = 2;
  end;
end;  

解决方案 »

  1.   

    必须在其他地方释放New(PRec)创建的内存,否则肯定会造成内存泄露,你可以返回一个boolean量来判断是否正确function GetRec(var ARec:TRec):boolean;
      

  2.   

    用這個比較好:function GetRec: TRec;
    begin
      //Result := nil;这样我就无法返回空值了
      if True then
        Result.Line1 = 1;
        Result.Line2 = 2;
      end;
    end;
      

  3.   

    aiirii如果返回空,我怎么表示呢,结构类型能返回nil吗
      

  4.   

    为什么非要返回nil呢?
    如果想表示一个错误,可以用raise Exception.Create('error');
      

  5.   

    Procedure GetRec(R:PRec)
    begin
      if r = nil then exit;
      
      R^.Line1 = 1;
        R^.Line2 = 2;
    end;
    我经常这样做,一般向函数传指针类型的(包括Object)参数,在调用的环境中创建和释放,不在函数中创建或释放。
      

  6.   

    当然要返回nil
    TMan = record
      ID: Integer;
      Name: string;
      Age: Intege;
    end
    PMan = ^TMan;function GetMan(ID: Integer): PMan
    begin
      if 找到 then
      begin
        Result.ID := xx;
        Result.Name := xx;
        Result.Age := xx;
      end
      else begin
        Result := nil;//这肯定是不行的,我想这样写Result.ID = -1,但总觉得不好
      end;
    end;function GetMain(ID: Integer): TMan
    begin
      if 找到 then
      begin
        Result.ID := xx;
        Result.Name := xx;
        Result.Age := xx;
      end
      else begin
        Result.ID = -1;
      end;
    end;  
    end;
    如果找到了我就回
      

  7.   

    不好意思,笔误
    function GetMan(ID: Integer): PMan
    begin
      if 找到 then
      begin
        Result.ID := xx;
        Result.Name := xx;
        Result.Age := xx;
      end
      else begin
        Result := nil;
      end;
    end;function GetMain(ID: Integer): TMan
    begin
      if 找到 then
      begin
        Result.ID := xx;
        Result.Name := xx;
        Result.Age := xx;
      end
      else begin
        Result.ID = nil;;//这肯定是不行的,我想这样写Result.ID = -1,但总觉得不好
      end;
    end;
      

  8.   

    你这两个函数写的都不对。且不说你语法错误。 
    if true thenend;
    那个Begin 去哪了?你这个程序能编译吗?
    另外你调用 Result.line1:=1 ;这个Result是一个指针,它指向谁呢?你这样写不报错才怪呢?
    正确的写法应该是:
    function GetRec: TRec;
    begin
      New(Result);  //分配内存
      if assigned(Result) then  //如果分配成功
      begin
        Result.Line1 = 1;   //向着两个赋值;
        Result.Line2 = 2;
      end;
    end;
    释放应该由调用该程序的负责。

      P:=GetRec;
      .....//对P的使用。
      dispose(P);//这句话就完成了对 GetRec中分配内存的释放(这句一定要,否则
      

  9.   

    function GetRec(var Rec: TRec):Boolean;
    // 返回值false/true...