Page 1 of 1

newbie: data structure

PostPosted: March 19th, 2005, 1:13 pm
by willy
i created linked list. i think it works but it doesnt. this is the my linked list declaration . I dont know why when try to access data lintasan(string) it just got accessviolation but the other is fine.

Code: Select all
//type list  of Path
  Ppath=^Tpath;
  data=record
      lintasan:string;
      plintasan:real;
      state:integer;
      id:integer;
  end;
  Tpath   =record
      Next   : Ppath;
      Info   : data;
   end;
   ListPath=record
      First   : Ppath;
  end;


i got the access violation message when i try to manipulate my linked list like this
Code: Select all
procedure testlistpath(var lpa:listpath)
var
x:integer;
temppath,newpath:ppath;

begin
x:=5;
while(x<=nbs)do begin
     GetMem(newpath,SizeOf(Tpath));
     Allocpath(newpath);
     newpath^.Info.id:=x;
     newpath^.Next:=nil;
     if(not(Assigned(LPa.First))) then begin
        Lpa.First:=newpath; temppath:=Lpa.First;
     end else begin
        temppath^.Next:=newpath;
        temppath:=temppath.Next;
     end;
      x:=x+1;
  end;
end;


Code: Select all
procedure Allocpath(item :Ppath);
//mengalokasikan sebuah path
begin
    new(item);
      item^.Info.lintasan:='';
      item^.Info.plintasan:=100;
      item^.Next:=nil;
end;

please help urgently got problems with deadline :(

PostPosted: March 21st, 2005, 12:58 am
by Kambiz
I tested your code as follow and no exception raised.

Code: Select all
const
  nbs = 10;

procedure TForm1.FormCreate(Sender: TObject);
var
  lp: ListPath;
begin
  lp.First := nil;
  testlistpath(lp);
end;

PostPosted: March 21st, 2005, 9:55 am
by Kambiz
By the way, why you are allocating memory for a node two times?

Code: Select all
procedure testlistpath(var lpa:listpath)
var
x:integer;
temppath,newpath:ppath;

begin
x:=5;
while(x<=nbs)do begin
     GetMem(newpath,SizeOf(Tpath)); //==========>> first time
     Allocpath(newpath);
     newpath^.Info.id:=x;
     newpath^.Next:=nil;
     if(not(Assigned(LPa.First))) then begin
        Lpa.First:=newpath; temppath:=Lpa.First;
     end else begin
        temppath^.Next:=newpath;
        temppath:=temppath.Next;
     end;
      x:=x+1;
  end;
end;

procedure Allocpath(item :Ppath);
//mengalokasikan sebuah path
begin
    new(item); //==========>> second time
      item^.Info.lintasan:='';
      item^.Info.plintasan:=100;
      item^.Next:=nil;
end;

The first time allocation is junk and should be removed.

In the other hand, the definition of your Allocpath procedure is incorrect. You pass the parameter as call by value, you allocate an item, you initialize the item, and then you lose it.

The correct definition is in this way:

Code: Select all
procedure Allocpath(out item :Ppath);