I'm quite new to C++, so as an excercise I've been trying to code a game using Raylib and C++, but I ran into an issue. I wanted to make minesweeper and for that I needed a grid which I wanted to represent with two bool arrays and because I wanted the player to input the size of the map I had to initialize the array on the heap.
game.h
#pragma once
#include <raylib.h>
class Game
{
bool* map;
bool* overlay;
int width, height;
public:
Game();
Game(int _width, int _height, int mines, int seed, int startX, int startY);
~Game();
void tick();
void draw() const;
};
Game.cpp
Game::Game(int _width, int _height, int mines, int seed, int startX, int startY)
{
map = new bool[width*height];
overlay = new bool[width*height];
width = _width;
height = _height;
for (int i = 0; i < width * height; i++)
map[i] = false;
for(int i = 0; i < width*height; i++)
overlay[i] = true;
SetRandomSeed(seed);
for(int i = 0; i < mines; i++)
{
int x = GetRandomValue(1, width), y = GetRandomValue(1, height);
while(map[(x+width*y)-1] || (x == startX && y == startY))
x = GetRandomValue(1, width), y = GetRandomValue(1, height);
map[(x+width*y)-1] = true;
}
}
void Game::draw() const
{
for(int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{
if(overlay[width*y+x])
DrawRectangle(x*10,y*10, 10, 10, (y+x)%2 == 0 ? DARKGRAY : LIGHTGRAY);
}
}
Main.cpp
#include <raylib.h>
#include "game.h"
int main(void)
{
InitWindow(800, 450, "raylib [core] example - basic window");
Game game(24, 24, 5, 0, 0, 0);
while (!WindowShouldClose())
{
//some stuff here
game.draw();
} // exception thrown here
CloseWindow();
return 0;
}
Exception screenshot from visual studio:
I've tested it and it crashes when I leave
for (int i = 0; i < width * height; i++)
map[i] = false;
for(int i = 0; i < width*height; i++)
overlay[i] = true;
this in the Game constructor.
Okay, thank you user4581301 for your comment. After checking the code I realized I had initialized the arrays before the width and height so the arrays were using uninitialized values for their size. I simply changed the order in which the values were initialized in the constructor from
map = new bool[width*height];
overlay = new bool[width*height];
width = _width;
height = _height;
to
width = _width;
height = _height;
map = new bool[width*height];
overlay = new bool[width*height];
and it worked.