简体   繁体   中英

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:

#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.

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. This exception is thrown after it has been compiled and it isn't marked as an error in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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