【问题标题】:Having trouble understanding this function return无法理解此函数返回
【发布时间】:2018-02-09 10:54:18
【问题描述】:

我正在使用在此处找到的以下代码来开始我的涉及树数据结构的项目。

struct node{

    int ID;
    struct node* next;
    struct node* child;
};

typedef struct node node;

node* new_node(int);
node* add_sibling(node*, int);
node* add_child(node*, int);


int main()
{
    int i;
    node *root = new_node(0);
    for (i = 1; i <= 3; i++)
        add_child(root, i);
}

node * new_node(int ID)
{
    node* new_node =(node*) malloc(sizeof(node));
    if (new_node) {
        new_node->next = NULL;
        new_node->child = NULL;
        new_node->ID = ID;
    }

    return new_node;
}

node* add_sibling(node* n, int ID)
{
    if (n == NULL)
        return NULL;

    while (n->next)
        n = n->next;

    return (n->next = new_node(ID));
}

node* add_child(node* n, int ID)
{
    if (n == NULL)
        return NULL;
    if (n->child)
        return add_sibling(n->child, ID);
    else
        return (n->child = new_node(ID));
}

我是 C/C++ 和一般编程的初学者。我想我了解除了 add_child 函数之外的所有代码。该函数似乎返回一个指向节点的指针,但是当它在 main 中调用时,它似乎被调用,就好像它是一个 void 函数。我本来想用这种方式调用函数

*root = add_child(root,i);

就像 new_node 的调用方式,或者将 add_child 编写为 void 函数,但是这两种修改都会导致错误(更不用说我发现代码中的实现 确实 工作)。我错过了什么?

【问题讨论】:

  • 你可以调用一个返回值的方法,只是不使用返回值。这就是你的主要工作。
  • 你认为作者这样写有什么原因吗?
  • 因为他根本不需要使用返回值,但在其他情况下可能会有用
  • 我明白了,谢谢。我看到我可以将其更改为 void 函数并获得相同的结果(在我不需要返回值的情况下)。

标签: c tree return void


【解决方案1】:

重写后的函数如下所示。

node* add_child(node* n, int ID)
{
    // For null pointer return null
    if (n == NULL)
    {
        return NULL;
    }

    // If element has child add a sibling to that child
    if (n->child)
    {
        node* sibling_for_child = add_sibling(n->child, ID);
        return sibling_for_child;
    }
    else
    {
        // Otherwise just add element as a child
        node* child_node = new_node(ID);
        n->child = child_node;
        return child_node;
    }
}

赋值的结果是一个赋值(*),就像这个链式赋值一样:

int a, b;
a = b = 3;

实际上是:

a = (b = 3);

b = 3;
a = b;

【讨论】:

  • 谢谢,你重写代码的方式更清晰了,我会用的。不过,我的困惑源于未使用的函数的返回,但上面的评论者为我澄清了这一点。
  • 这如何解决 OP 的顾虑:“但是当它在 main 中调用时,它似乎被称为 void 函数”?
  • 它没有。这个答案更多的是关于“我想我理解除了 add_child 函数之外的所有代码”
猜你喜欢
  • 2012-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
相关资源
最近更新 更多