【问题标题】:Use of static in a function [duplicate]在函数中使用静态[重复]
【发布时间】:2014-05-16 22:49:12
【问题描述】:
#include<stdio.h>
#include<malloc.h>

struct node
{
    int data;
    struct node* left;
    struct node* right;
};
struct node* newNode(int data)
{
    struct node* node=(struct node*)malloc(sizeof(struct node));
    node->data=data;
    node->left=NULL;
    node->right=NULL;

    return (node);
};

int height(struct node* root)
{
    static int lheight,rheight;
    if(root==NULL)
        return;
    else
    {
        lheight=height(root->left)+1;
        rheight=height(root->right)+1;
        if(lheight>rheight)
            return lheight;
        else
            return rheight;
    }

}

int main()
    {
          struct node* root=newNode(1);
          root->left=newNode(2);
          root->right       = newNode(3);
          root->left->left  = newNode(4);
          root->left->right = newNode(5);
          printf("%d",height(root));
          return 0;
    }

这个程序给出了两种不同的结果。对于上面我使用静态的程序,一个是 2,如果不使用静态,则为 3。请用static解释输出变化的原因。

【问题讨论】:

  • 请在提问前进行搜索。
  • 我无法理解这个特定问题的区别。
  • 不,不是这样。您希望有人做我们不做的功课。请阅读链接。
  • 我已经浏览了链接。我完全明白这意味着什么。但是为什么这个特定代码有两个不同的输出是我无法理解的。
  • 我听起来你正在做作业/面试工作..都不应该回答

标签: c static


【解决方案1】:

当您声明一个局部变量static 时,该变量只有一个副本,而不是每次调用该函数时都有一个单独的副本。所以当你递归调用height()时,它会覆盖调用函数中正在使用的变量。

这就是正在发生的事情。首先该函数:

lheight = height(root->left)+1;

这会将lheight设置为当前节点左分支的高度+1。然后你调用:

rheight = height(root->right)+1;

在对height 的递归调用中,它再次调用:

lheight = height(root->left)+1;

所以现在lheight 不再包含父级左分支的高度,它包含右子级左分支的高度+1。

如果你不使用static,每个递归级别都有自己的变量,当你进行递归调用时它们不会被覆盖。

【讨论】:

  • 我明白这一点。但是为什么这里有两个不同的输出呢?
  • 单步调试函数,可以使用调试器,也可以将变量写在纸上,看看会发生什么。
  • 但是有两个不同的静态变量,一个是lheight,另一个是rheight。
  • 但是您在每次递归调用期间都会更新这两个变量。所以在你设置了lheight之后,你再在右边的分支上调用height,它会覆盖lheight
  • 知道了。谢谢你..!
猜你喜欢
  • 1970-01-01
  • 2020-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
相关资源
最近更新 更多