c - 在函数中使用 static

标签 c static

#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;
    }

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

最佳答案

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

这就是发生的事情。首先该函数执行以下操作:

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

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

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

在对 height 的递归调用中,它再次执行以下操作:

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

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

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

关于c - 在函数中使用 static,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23705630/

相关文章:

C 程序不能正确比较字符

c - Flex Bison 计算器不打印结果

c - 在 Visual Studio Code 中编译 C 程序时出错

c# - 通过字符串名称获取属性值

C++:使用析构函数删除指针静态 vector 中的对象?

c - 我如何在控制台上处理 c 中的箭头键?

c - 误解传递给 C 中函数的数组指针

c# - 静态只读字段的初始化顺序

c# - 静态方法如何调用虚方法?

java - 静态 block 初始化