gpt4 book ai didi

c - 返回结构指针

转载 作者:行者123 更新时间:2023-12-04 11:27:33 24 4
gpt4 key购买 nike

我对 code 感到困惑下面:

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

struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);

/* return the (unchanged) node pointer */
return node;
}
}

newNode 返回指向它已分配的结构的指针。然而,在 insert 函数的第 6 行中,newNode 的返回值没有被分配给任何东西,它只是被调用了。代码如何进一步向下能够使用新创建的节点结构?

最佳答案

如果树不是是空的,下面的代码将会运行。因此,当步骤 .2 中的代码运行时,步骤 .1 中的代码不会运行。

当递归展开时,您可以看到分配操作正在发生,例如:

node->left  = insert(node->left, data);

哦,正如 ThunderWiring 所说,do not cast malloc!

关于c - 返回结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32550492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com