无法理解此return语句的功能,如果没有它,则会发生运行时错误

问题描述 投票:-3回答:1

在下面if函数的bstcreate()语句中,如果我删除了return语句,则会发生运行时错误。为什么会这样?

即使没有while语句,进程也不会转到return语句,因为所有的语句都会被执行吗?

这是下面的代码:

struct Node{
    struct Node *lchild;
    int data;
    struct Node *rchild;

}*root=NULL;

void bstcreate(int key)
{
    struct Node*t=root;
    struct Node*p,*r=NULL;
    if(root == NULL)
    {
        p = (struct Node*)malloc(sizeof(struct Node));
        p->data = key;
        p->lchild = p->rchild = NULL;
        root = p;
        return;
    }

    while(t)
    {
        r=t;
        if(key<t->data)
        {
            t=t->lchild;
        }
        else
        {
            t=t->rchild;
        }
    }
    p = (struct Node*)malloc(sizeof(struct Node));
    p->data = key;
    p->lchild = p->rchild = NULL;

    if(r->data>key)
    {
        r->lchild=p;
    }
    else
    {
        r->rchild=p;
    }
}
c++ c data-structures tree binary-search-tree
1个回答
1
投票

如果列表为空,则bstcreate()会将root设置为新的Node,然后由于没有其他事情可做,因此期望立即退出。 return语句执行该退出。由于该函数被声明为返回void,因此无需向return提供值。

t初始化为rootr初始化为NULL。如果删除return语句,并且输入时rootNULL,则t最初为NULL,导致跳过while循环,然后在访问r成员时发生崩溃],因为r仍为NULL,因为循环没有将r分配为指向任何地方。

© www.soinside.com 2019 - 2024. All rights reserved.