Search code examples
cdata-structuresdynamic-memory-allocation

Dynamic structure initialization and counter implementation


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


Solution

  • 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);
    }