[英]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.