2

How can i Initial This Code?

type
  PPNode = ^PNode;
  PNode  = ^Node;
  CNode = array of PPNode;

  Node = record
    key: Integer;
    next: PNode;
    prev: PNode;
  end;

i use this way :

function TForm1.chained_hash_init(n: Integer): CNode;
var
  A: Cnode;
begin
  ...
  SetLength(A, N);
  Result := A;
  ...
end;

But I have Error in Memory For this access:

procedure TForm1.btn1Click(Sender: TObject);
var
  pcnArr: CNode;
begin    
  SetLength(pcnArr, 19);
  pcnArr := chained_hash_init(19);
  ShowMessage( IntToStr(pcnArr[i]^^.key)) );     // I have Problem Here :(     
end;

How Can I Initial Cnode ?

TLama
  • 75,147
  • 17
  • 214
  • 392
mohammadkad
  • 105
  • 1
  • 10

1 Answers1

3

You didn't initialized pcnArr[i] before ShowMesage. So you get "access violation" error.

So you should initialize pcnArr for example:

function TForm1.chained_hash_init(n: Integer): CNode;
var
  A: Cnode;
  i:integer;
  P:PNode;
begin
  ...
  SetLength(A, N);

  for i:=0 to N-1 do
  begin
    new(A[i]);
    new(A[i]^);
    with A[i]^^ do
    begin
        key:=0; 
        next:=nil; 
        prev:=nil; 
    end;  
  end;

  Result := A;
  ...
end;
valex
  • 23,966
  • 7
  • 43
  • 60
  • Are you sure you can do A[i]^^? I haven't try it but it looks suspicious. – mg30rg Aug 13 '13 at 14:24
  • 1
    @mg30rg `something^^` is ok but you can't do `^^someType`. The former case can resolve the type at each step but the latter does not enforce a type in "the middle". – J... Aug 13 '13 at 16:39
  • @J... Thanks, it is pretty good to know! I'm pretty new to Delphi (used to develop in C++ and C# for years, but recently moved to an enterprise which utilities Delphi), and I am in an endless doubt in pointer operations which seem to be a bit over-complicated. – mg30rg Aug 14 '13 at 07:22