user9215386
user9215386

Reputation:

variable may not have been initalised

I am in the process of writing a maze generation algorithm to randomly generate a maze through recursive backtracking.

When the program compiles and the procedure "controller" is used to pick a random direction, I am getting an "access violation"

I'm also getting messages saying: "variable 'i' may not have been initialised" "variable 'j' may not have been initialised"

Are the above errors related to the access violation, and if so what is causing it?

procedure TfrmMazeGame.btnSTartGameClick(Sender: TObject);
var
  i, j: integer;
begin
  lblTitle.Visible := false;
  btnStartGame.Visible := false;
  btnExit.Visible := false;
  StrGridMaze.Visible := true;

  for i := 0 to 19 do
  begin
    for j := 0 to 19 do
    begin
      maze[i, j] := TCell.Create;
    end;
  end;
  fillarray (maze);
  GenerateMaze(maze);
end;

procedure TfrmMazeGame.Controller(maze: TMaze; CurrentCell: TCell);
type
  TDirection = (up, down, left, right);
var
  Direction: TDirection;
  i, j: integer;
begin
  Direction := TDirection(random(3));
  case Direction of
    up:
      begin
        CurrentCell := maze[i, j - 1];
        CurrentCell.Wall := false;
      end;
    down:
      begin
        CurrentCell := maze[i, j + 1];
        CurrentCell.Wall := false;
      end;
    left:
      begin
        CurrentCell := maze[i - 1, j];
        CurrentCell.Wall := false;
      end;
    right:
      begin
        CurrentCell := maze[i + 1, j];
        CurrentCell.Wall := false;
      end;
  end;
end;

procedure TfrmMazeGame.fillArray(maze: TMaze);
var
  i, j: integer;
begin
  for i := 0 to 19 do
  begin
    for j := 0 to 19 do
    begin
      maze[i,j].Wall := true;
    end;
  end;
end;

procedure TfrmMazeGame.FormCreate(Sender: TObject);
begin
  position := poScreenCenter;
  StrGridMaze.Visible := false;
end;

procedure TfrmMazeGame.GenerateMaze(maze: TMaze);
var
  CurrentCell: TCell;
begin
  CurrentCell := maze[0, 0];
  maze[0, 0].Wall := false;
  Controller(maze, CurrentCell);
end;

Upvotes: 1

Views: 123

Answers (1)

David Heffernan
David Heffernan

Reputation: 612874

In the Controller function you don't initialize the local variables i and j. The compiler told you that. It is correct.

Because of this the variables values are undefined and that can certainly explain the access violation because you access the array out of bounds.

Upvotes: 3

Related Questions