Implementing an Enqueue function (PASCAL)

270 views Asked by At

I'm having trouble getting the queue in my program to work. Every adjustment I've tried has resulted in an 'ERangeError: Range check error'. I know this is because the program is trying to access something that doesn't exist, but I cannot figure out how to fix it. Here is my queue implementation...

node = record //Square on chessboard
  x: integer; //Row coordinate
  y: integer; //Col coordinate
  d: integer; //Distance from starting position
  next: ^node;// (for the queue)
 end; //node
coord = ^node;//'Coordinates'
queue = record//Queue w/ Linked List
  head: coord;
  tail: coord;
 end; //queue

procedure init(var q: queue);
  begin
    q.head := nil;
    q.tail := nil;
   end; //init
function isEmpty(const q: queue): boolean;
 begin
  isEmpty := (q.head = nil);
 end; //isEmpty
procedure push(var q: queue; m, n, o: integer);
 var C: coord;
 begin
  new(C);
    C^.x := m;
    C^.y := n;
    C^.d := o;

  if q.head = nil then begin
    q.head := C;
    q.tail := q.head;
    end
  else begin
    q.tail^.next := C;
    q.tail := C;
    end;
 end; //push
procedure pop(var q: queue; out m: int; out n: int; out o: int);
 var C: coord;
 begin
  m := q.head^.x;
  n := q.head^.y;
  o := q.head^.d;

  C := q.head;
  q.head := q.head^.next;
  dispose(C);
  if q.head = nil then q.tail := nil;
 end; //pop

...and here is the main part of the function that is interacting with it.

while not isEmpty(q) do begin
  pop(q, row, col, dst);
    new(crd2);
    crd2^.x := row;
    crd2^.y := col;
    crd2^.d := dst;

  if valid(B, crd2) and not visited[crd2^.x, crd2^.y] then
    visited[crd2^.x, crd2^.y] := true; //Mark square as visited
  if (crd2^.x = Gl^.x) and (crd2^.y = Gl^.y) then
    exit(crd2^.d); //Goal Check

  for i := 1 to 8 do begin
    crd2^.x := crd2^.x + mvmtX[i];
    crd2^.y := crd2^.y + mvmtY[i];

    if valid(B, crd2) and not visited[crd2^.x, crd2^.y] then begin
      crd2^.d := crd2^.d + 1;

      push(q, crd2^.x, crd2^.y, crd2^.d);

     end;//if valid(B, crd)...

  end;//for i
 end;//while not isEmpty(q)
 exit(crd^.d);
end;

I thought I had covered the issue by adding enough new(node) calls in the program, but the error still persists. I'm really at a loss and would appreciate any clarity you could offer.
I would email my professor but he is skiing right now and is hard to reach. Thank you for any advice :)

0

There are 0 answers