Jane Doe
Jane Doe

Reputation: 187

Using Structs in C

Hi im building a simple game in c (im new to the language). Im using the following structs:

typedef struct
{
    int adjacent_mines;
    bool revealed;
    bool is_mine;
} Tile;

struct GameState
{
    Tile tiles[NUM_TILES_X][NUM_TILES_Y];
};
typedef struct GameState GameState;

Im wondering how to properly call and set the structs? I have the following code where i would like to set state of each Tile.

void intialize_mines(){
    for (int i =0; i < NUM_TILES_X; i++){
        for (int j =0; j < NUM_TILES_Y; j++){
            tiles[i,j].revealed = false;
        }
    }
}

But according to my console output i have done this incorrectly. How would i go about setting this correctly?

Upvotes: 1

Views: 178

Answers (3)

P.W
P.W

Reputation: 26800

For a multi-dimensional array like tiles, you have to specify array subscript of each dimension within [] like this:

tiles[i][j].revealed = false;

This means that revealed belonging to jth column of ith row of tiles is set to false.

And you will have to define a structure variable of the type GameState before performing any operations on it.

GameState initGS;

void intialize_mines(){
    for (int i =0; i < NUM_TILES_X; i++){
        for (int j =0; j < NUM_TILES_Y; j++){
            initGS.tiles[i][j].revealed = false;
        }
    }
}

Upvotes: 1

Kami Kaze
Kami Kaze

Reputation: 2080

struct GameState just declares a type (just as int is just a type). You have to create a real struct in memory with GameState foo; similar to a normal variable (int foo;). And you can not access the contents of a struct without referencing the struct like foo.tiles. tiles on it's own is not known in this scope.

Afterwards you can access the struct with foo.tiles[i][j].revealed.

But to have access to this struct in your function you either have to pass it to the function as a pointer or declare the struct in filescope ( also called global). I would prefer the first version it is clearer an more function like.

Your function would look like this:

void intialize_mines( GameState *foo){
    for (int i =0; i < NUM_TILES_X; i++){
        for (int j =0; j < NUM_TILES_Y; j++){
            foo->tiles[i][j].revealed = false; // -> is a special operator for pointers to structs. It's the same as (*foo).
        }
    }
}

the corresponding function call would be:

GameSate bar;
intialize_mines( GameState &bar);

You should also check how to use multidimensional arrays. You declared it correctly with two seperate [] but in your function you use [x,y] which is not correct in C. It would be the same as in the declaration tiles[i][j]

Upvotes: 3

Jorg B Jorge
Jorg B Jorge

Reputation: 1119

You just missed to instantiate a GameState structure.

GameState gs;

void initialize_mines() {
    for (int i =0; i < NUM_TILES_X; i++) {
        for (int j =0; j < NUM_TILES_Y; j++) {
            gs.tiles[i][j].revealed = false;
        }
    }
}

Upvotes: 0

Related Questions