繁体   English   中英

在 c++ 中用随机数抛出异常

[英]exception thrown with random numbers in c++

我正在尝试制作一款需要伪随机数将敌人设置为随机点的游戏。 所以我尝试包含stdlib header 文件并使用srand ,然后使用rand为敌人获取随机数,我的代码直到第一个srand看起来像这样:

#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include <time.h>

int screenWidth = 70, screenHeight = 80;

class Enemy {
public:
    int column, lives;
    Enemy() {};
    Enemy(int nColumn, int nLives) {
        column = nColumn;
        lives = nLives;
    }
};
int main()
{
    wchar_t *screen = new wchar_t[screenWidth * screenHeight];
    HANDLE hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
    SetConsoleActiveScreenBuffer(hConsole);
    DWORD bytesWritten = 0;
    int x = 0, y = 0, width = 10, height = 10;
    std::wstring canvas = L"";
    wchar_t *title = new wchar_t[8];
    wsprintf(title, L"retro shooter");
    SetConsoleTitle(title);
    int enemiesLength = screenWidth / width;
    Enemy* enemies = new Enemy[enemiesLength];
    srand(time(NULL)); // It throws the error at this line
    for (int i = 0; i < enemiesLength; i++) {
        if (rand() % 2) enemies[i] = Enemy(i, 1);
    }
    // the code doesn't end here that's why I didn't put out the closing curly bracket

上面的代码给了我错误/异常:

retroShooter.exe 中的 0x76EDE496 (ntdll.dll) 抛出异常:0xC0000005:访问冲突读取位置 0x183A0FA2。

我试过使用向量,但例外是一样的。 我也试过include -ing cstdlib like: #include <cstdlib>但异常是完全一样的。 此异常在编译后抛出,并且在 visual studio 中未标记为错误

这可能是问题所在:

wchar_t *title = new wchar_t[8];   // 8 is a lot shorter
wsprintf(title, L"retro shooter"); // than 14

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM