C语言 使用指针在递归函数中创建计数器



我想数一下函数移动中有多少次移动。如果可能的话,我想为它使用指针,以便我可以了解更多信息。

我使用全局创建了一个计数器,但现在我想使用指针,但我尝试的所有内容都失败了。

void move(unsigned int moves, char source, char spare, char dest)
{
    if (moves == 0) {
    /* no move: nothing to do */
    }
    else {
        move(moves - 1, source, dest, spare);
        printf("Move disk %d from pole %c to pole %c.n", moves, source, 
dest);
        move(moves - 1, spare, source, dest);
    }
}
int main()
{
    char source = 'A';
    char spare = 'B';
    char dest = 'C';
    int moves = size();
    move(moves, source, spare, dest);

    return 0;
}

如果我理解正确,您想更改参数列表中给定的变量。可以使用指针执行此操作。例如:

void move(int *pa)
{
    (*pa)++;  // increase the counter by one
    if (*pa < 5) move(pa);
}
void main(void)
{
    int a = 0;
    move(&a);
}

最新更新