Search code examples
c++arraysrandomdice

generate random numbers and put them in an array


I'm looking to write a little dice game called Farkle (you may know it from Kingdom come delivarance) in C++ but I'm still learning, so I have some trouble with it. atm I'm trying to roll 6 dice and put every rolled number in an array to be able to work with it afterwards. everything seem to work fine but Visual Studio ist outputting this error Code:

Run-Time Check Failure #2 - Stack around the variable 'die' was corrupted.

this is my code:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;


void dice() {
    int die[5];
    int i = 1;
    while (i <= 6) {
        die[i] = rand() % 6 + 1;
        cout << die[i];
        i++;
    }
}


int main()
{
    srand(time(NULL));
    dice();
    system("STOP");
    return 0;
}

is ths actually the right approach for this kind of programm?


Solution

  • You have 2 problems in your code:

    1. The size of your array is 5, but you access 6 indices (1 to 6), you can avoid this by changing the <= to < in the condition.

    2. The indices of an array in C++ start with 0, but you start with 1. You can fix that if you change each die[i] to die[i-1] in your code.

    Another approach (fixing both problems) would be to initialize i=0 and go with while (i < 5)