0

Lets say I have this structure

typedef struct Stack
    {
        int firstPlayerScore;
        int secondPlayerScore;
        int gamesCount;

    }Stack;

and this function to ini the values:

void initStack(Stack *g)
{
    g->firstPlayerScore = 0;
    g->secondPlayerScore = 0;
    g->gamesCount = 0;

}

The problem is here, I need to be able to reset other values, but keep g.gamescount and add +1 each time gameStart function runs. Its probably a simple solution ,but I am starting to lose my mind, thank you.

void gameStart(int choice) {

    Stack g;
    initStack(&g);

    ++g.gamesCount; // this works only once, then is reset again to 0. 
     {
       // do stuff
     }
}

Cant do differently, since I believe Structure need to be inicialized. Maybe it is possible to inicialize only once somehow?

P.S I cant use global variables

Simas
  • 17
  • 4

2 Answers2

1

You need to allocate memory for the struct Stack variable g. You do not need global variables, what you need is to just while declaring g you need to call malloc function to allocate memory of the size of the struct type. It looks like this:

void gameStart(int choice) {

    Stack *g = (Stack *) malloc(sizeof(Stack));
    initStack(g);

    ++g->gamesCount; // this works only once, then is reset again to 0. 
    {
        // do stuff
    }
}

Malloc returns you void *, so it is better to typecast to Stack *. Also, you need to create Stack *, as it is a struct type and requires pointer tpye. Hope this will help you.

Gor Stepanyan
  • 326
  • 2
  • 5
  • 1
    `Malloc returns you void *, so it is better to typecast to Stack *` [Do I cast the result of malloc?](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – KamilCuk Dec 08 '19 at 15:03
1

Pass a pointer to the state to your function:

void gameStart(Stack *g, int choice) {
    ++g.gamesCount; // this works only once, then is reset again to 0. 
     {
       // do stuff
     }
}

Then inside main():

int main() {
    Stack g;
    initStack(&g);
    gameStart(&g, 49);
}
KamilCuk
  • 120,984
  • 8
  • 59
  • 111