【问题标题】:C - Unable to index inside a recursive functionC - 无法在递归函数内建立索引
【发布时间】:2018-12-07 11:27:46
【问题描述】:

我试图在递归函数中索引一个数组,但是索引没有按预期工作,因为我无法在函数内增加一个计数器。问题可以简化为以下代码。

这里的根是一个指向节点结构的指针,它是一个简单的树。

递归函数:

void inorder(node *root, int in_count)
{
    if (root != NULL)
    {       

        inorder(root->left, in_count);
        printf("key is %d and count is %d\n", root->KEY, root->node_count, in_count++);

        //index array arr[in_count];

        inorder(root->right, in_count);
    }
}

主要:

int main()
{
    int in_count =0;
    printf("Inorder traversal of the given tree \n");
    inorder(root, in_count);
}

输出:

Inorder traversal of the given tree 
key is 1 and count is 0
key is 2 and count is 0
key is 2 and count is 1
key is 2 and count is 2
key is 3 and count is 0
key is 5 and count is 1
key is 7 and count is 2
key is 9 and count is 3
key is 12 and count is 0

我预计 in_count 会从 0 增加到 8,但事实并非如此。为什么计数会重置?任何建议将不胜感激。

【问题讨论】:

    标签: c function recursion


    【解决方案1】:

    您需要传递count 作为参考。

    void inorder(node *root, int *pIn_count)
    {
        if (root != NULL)
        {       
    
            inorder(root->left, pIn_count);
            printf("count is %d \n", (*pIn_count)++);
    
            //index array arr[in_count];
    
            printf("%d ", root->KEY);
            inorder(root->right, pIn_count);
        }
    }
    

    来自main

    int main()
    {
        int in_count =0;
        printf("Inorder traversal of the given tree \n");
        inorder(root, &in_count);
    }
    

    【讨论】:

    • 是的,这是解决方案之一。但是您能否简要解释一下为什么它适用于引用传递而不适用于值传递?
    • @VladRusu 因为否则您只会将副本传递给被调用函数,而该副本永远不会复制回调用函数中可见的实例。
    • @VladRusu 我不是来教什么是通过引用传递和通过值传递。我已经给出了关键字(“参考”)。让他做研究。
    • 我知道 :) 我要求它是因为在问题中 OP 询问为什么要重置计数,所以我认为一些解释会对他有所帮助。此外,使用全局 in_count 是另一种有效的解决方案。
    【解决方案2】:

    您也可以使用静态变量来实现结果。在函数中将 count 声明为 static int count=0;,并像以前一样递增它。静态变量不存储在堆栈中,它们存储在单独的段中,因此值将保持不变。

    计数重置的原因是在递归调用中,内部调用所做的更改不会反映在调用者上。被调用者使用一个新的 count 副本,其更改不会反映在调用者中。

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      相关资源
      最近更新 更多