[英]exception thrown with random numbers in c++
I'm trying to make a game which requires pseudo random numbers to set the enemies to random spots.我正在尝试制作一款需要伪随机数将敌人设置为随机点的游戏。 So I tried including the
stdlib
header file and used srand
before getting random numbers for the enemies using rand
, my code until the first srand
looks like this:所以我尝试包含
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
The code above gives me the error/exception:上面的代码给了我错误/异常:
Exception thrown at 0x76EDE496 (ntdll.dll) in retroShooter.exe: 0xC0000005: Access violation reading location 0x183A0FA2.
retroShooter.exe 中的 0x76EDE496 (ntdll.dll) 抛出异常:0xC0000005:访问冲突读取位置 0x183A0FA2。
I have tried using vectors but the exception is the same.我试过使用向量,但例外是一样的。 I have also tried
include
-ing cstdlib
like: #include <cstdlib>
but the exception is the exact same.我也试过
include
-ing cstdlib
like: #include <cstdlib>
但异常是完全一样的。 This exception is thrown after it has been compiled and it isn't marked as an error in visual studio此异常在编译后抛出,并且在 visual studio 中未标记为错误
This is robably the issue:这可能是问题所在:
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.