C语言 动态结构初始化和计数器实现



假设我有这个结构

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

和这个函数来初始化值:

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

问题就在这里,我需要能够重置其他值,但保留 g.gamescount 并在每次 gameStart 函数运行时添加 +1。这可能是一个简单的解决方案,但我开始失去理智,谢谢。

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

不能做不同的事情,因为我认为结构需要被初始化。也许可以以某种方式只初始化一次?

附言我不能使用全局变量

将指向状态的指针传递给函数:

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

然后在main()里面:

int main() {
Stack g;
initStack(&g);
gameStart(&g, 49);
}

您需要为结构 Stack 变量 g 分配内存。你不需要全局变量,你需要的只是在声明g的同时,你需要调用malloc函数来分配结构类型大小的内存。它看起来像这样:

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 返回 void *,因此最好将类型转换为 Stack *。此外,您需要创建 Stack *,因为它是一种结构类型并且需要指针 tpye。 希望这对您有所帮助。

最新更新