vendredi 26 juin 2020

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];
    for (int i = 0; i < enemiesLength; i++) {
        srand(time(NULL)); // It throws the error at this line
        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 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




Aucun commentaire:

Enregistrer un commentaire