C program run-time error

Code compiles fine. Errors out at comment

Objective: User guesses values until guessing correctly. All guesses are intended to be stored and presented at end of game.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Guess game

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

typedef struct {
    int* guess;
    int val;
    int size;
    int length;
} Game;

int menu(void) {
    char option;
    puts("(P)lay");
    puts("(Q)uit");
    printf(">> ");
    scanf("%c", &option);
    if (option == 'p' || option == 'P')
        return 1;
    else
        return 0;
}

int diff(void) {
    int lvl;
    puts("Lvl 1 | Range:  250");
    puts("Lvl 2 | Range:  500");
    puts("Lvl 3 | Range: 1000");
    puts("-------------------");
    printf("Choose diificulty | 1 | 2 | 3 |");
    printf("\n>> ");
    scanf("%d", &lvl);
    if (lvl == 1)
        return 250;
    else if (lvl == 2)
        return 500;
    else if (lvl == 3)
        return 1000;
    else
        return -1;
}

int play(Game* game) {
    system("cls");
    do {
        printf("Guess %d\n>> ", game->length + 1);
        if (scanf("%d", game->guess[game->length])) {       //<- Errors here
            game->length++;
        } else
            puts("Invalid Input");
    } while (game->guess[game->length] != game->val 
             && game->length < game->size);
}

int main(void) {
    Game game;
    game.size = 64;
    game.length = 0;
    printf("guessGame V_1\n\n");
    if (menu()) {
        game.val = (rand() / (double)RAND_MAX) * diff();
        play(&game);
    }
    return EXIT_SUCCESS;
}
Last edited on
guess is an uninitialized pointer. You need to allocate some memory for the array. The simplest thing is to make it a regular array with a maximum size that you represent with a macro constant. Alternatively you can dynamically extend it. But you need to do one or the other. (EDIT: Looking again at your code, you have a size and length variable so I assume you meant to make it dynamic. Usually we call those capacity and size, respectively, like the library containers.)

In the future, be sure to paste the exact error message, too.
Last edited on
Oh I see. Just got out of an introductory class where we had to use buffers like this, but rarely made them, so I must have forgotten to allocate as you said.

I'll be sure to paste the error message when I have one (it was a run-time error so there wasn't a message besides "program has stopped worked")
Topic archived. No new replies allowed.