Raylib 在堆上创建数组时崩溃

问题描述 投票:0回答:1

我对 C++ 还很陌生,因此作为练习,我一直在尝试使用 Raylib 和 C++ 编写游戏代码,但遇到了问题。我想制作扫雷游戏,为此我需要一个网格,我想用两个布尔数组来表示它,并且因为我希望玩家输入地图的大小,所以我必须初始化堆上的数组。

游戏.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;
};

游戏.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);
        }
}

主要.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;
}

来自 Visual Studio 的异常截图:

我测试过它,当我离开时它崩溃了

for (int i = 0; i < width * height; i++)
    map[i] = false;
for(int i = 0; i < width*height; i++)
    overlay[i] = true;

Game 构造函数中的 this。

c++ arrays heap-memory raylib
1个回答
0
投票

好的,谢谢4581301用户的评论。检查代码后,我意识到我已经在宽度和高度之前初始化了数组,因此数组的大小使用了未初始化的值。我只是更改了构造函数中初始化值的顺序

map = new bool[width*height];
overlay = new bool[width*height];
width = _width;
height = _height;

width = _width;
height = _height;
map = new bool[width*height];
overlay = new bool[width*height];

并且成功了。

© www.soinside.com 2019 - 2024. All rights reserved.