我在程序中定义了:
type
    MyPoint=^MyStruct;
    MyStruct=Record
      cUnitCode: String;
      cShortName: String;
      ID: Integer;
      nFatherID: Integer;
    end;运行时提示行:stack overflow,如何解决呢?更郁闷的是,我在递归里用到了myPoint,如果在递归当中添一个showmessage,可以运行18次,如果不showmessage的话,第二次运行递归就报错。并且不是stack overflow的错误。

解决方案 »

  1.   

    我是把c#的代码翻译成delphi的,在c#下,没遇到问题,可是在delphi里碰到这种问题,真是郁闷第一次在递归里使用record,摸索中
      

  2.   

    你应该传结构的指针进去(包括用MyPoint变量代替MyStruct变量或者MyStruct变量前加上const或var修饰词)而不应该把整个结构传进去, 传结构变量的话会先在堆栈中复制整个结构一遍,这样递归调用的话很快就把堆栈占满了。
      

  3.   

    另外需要避免在递归过程中使用占大内存的局部变量比如
    var
      Buffer: array [0..100] of MyStruct;
    这种。因为这些变量都在栈中。每次进入过程时都将在堆栈中分配这块内存。这样几次堆栈就会用完。如果要使用这类大结构局部变量时最好用动态分配或者使用全局变量(这样这块内存本身就不会占用堆栈,堆栈中只需要分配4字节的一个指针)
      

  4.   

    我的递归代码:
    function TForm1.recursionDrawNode(tempNode: TTreeNode; theRecord: MyPoint): TTreeNode;
    var
        theTempTreeNod: TTreeNode;
        str: String;
    begin
        if (tempNode = nil) then
        begin
            Application.MessageBox('单位清单数据错误,原因:找不到父节点,可能是数据表数据混乱造成!', '提示',MB_OK OR MB_ICONWARNING);
            Result := nil;
            Exit;
        end;
        if theRecord.nFatherID = myPoint(tempNode.Data)^.ID then
        begin
            str := theRecord.cUnitCode + StrSpace + theRecord.cShortName;
            theTempTreeNod := RzCheckTree1.Items.AddChild(tempNode, str);
            theTempTreeNod.Data := theRecord;
    //下面这个showmessage的话,就出现内存引址错误???真是奇怪的很?
    showmessage('Code=' + myPoint(theTempTreeNod.Data)^.cUnitCode + ' ID =' + Inttostr(mypoint(theTempTreeNod.Data)^.ID));
            Result := theTempTreeNod;
            Exit;
        end
        else
        begin
    theTempTreeNod := recursionDrawNode(theTempTreeNod.Parent, theRecord);
            Result := theTempTreeNod;
            Exit;
        end;
    end;自己感觉应该没有问题啊???大家帮忙分析下,问题出现在哪里?
      

  5.   

    自己搞定发现个特弱的问题
    theTempTreeNod := recursionDrawNode(theTempTreeNod.Parent, theRecord);
    这句错了,应该是
    theTempTreeNod := recursionDrawNode(tempNod.Parent, theRecord);揭帖