简体   繁体   中英

Need Help for C Program

For an assignment I am writing code that counts the number of times the sum of 2 rolled dice has been calculated... For example if die 1 is 5 and die 2 is 6, then the value of timesRolled[(die 1 + die 2)] will be incremented. The code is below, which demonstrates my logic. The values that are returned are garbage and I need help determining where I went wrong on this. Thanks in advance!

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>

int main() {
    int i = 0;         // Loop counter iterates numRolls times
    int numRolls = 0;  // User defined number of rolls
    int timesRolled[] = { 0 };
    int pointerVal = 0;
    int rollNumber = 0;
    int die1 = 0;      // Dice values
    int die2 = 0;      // Dice values
    int rollTotal = 0; // Sum of dice values

    printf("Enter number of rolls: ");
    scanf_s("%d", &numRolls);
    srand(time(0));

    if (numRolls >= 1) {
        // Roll dice numRoll times
        for (i = 0; i < numRolls; ++i) {
            die1 = rand() % 6 + 1;
            die2 = rand() % 6 + 1;
            rollTotal = die1 + die2;
            ++timesRolled[(rollTotal)];
            printf("\nRoll %d is %d (%d+%d)",(i + 1), rollTotal, die1, die2);
        }
        printf("\n\nDice roll statistics: \n");
        for (pointerVal = 1; pointerVal <= 12; ++pointerVal) {
            printf("%ds: %d\n", pointerVal, timesRolled[(pointerVal)]);
        }   
    }
    else {
        printf("Invalid rolls. Try again.\n");
    }

    _getch();
    return 0;
}

You declared:

int timesRolled[] = { 0 };

That creates an array timesRolled of length 1 . But inside the for loop you are incrementing

++timesRolled[(rollTotal)];

Which can cause Buffer Overflow if rollTotal is greater than 0 . Because then you are trying to access an array element which is not defined. That will lead you to Undefined Behavior .

Same will happen in the printf() too:

printf("%ds: %d\n", pointerVal, timesRolled[(pointerVal)]);

So first determine what can be the largest length of timesRolled . Then declare and initialize it. For example:

int timesRolled[13] = { 0 }; //timesRolled is now an array of length 13

You are accessing array element which is not defined as size of array is 1 and pointerVal<=12 :

for (pointerVal = 1; pointerVal <= 12; ++pointerVal) {
            printf("%ds: %d\n", pointerVal, timesRolled[(pointerVal)]);

Replace:

int timesRolled[] = { 0 } with int timesRolled[13] = { 0 }

As sum of Dices will be max 12.

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