c - 返回结构指针

标签 c

我对 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/

相关文章:

Cython:链接到库和调用函数

c - 为什么我的 strcmp() 失败了?

c - xlib半透明窗口背景

c - 如何正确地将十进制 MIDI 弯音值分成 2 个分开的 7 位值?

c - 如何确定 linux 串行端口上剩余的写入/输出缓冲区空间量?

c - 使用矩阵作为一维数组参数

c - 为什么在 pthread_join 中 retval 是一个 void**?

c - 在 C 中的 opengl 中绘制纹理

c - scanf 格式说明符,用于从一组字符中读取零个或多个字符

c - 如何用C语言为 "Makefile"游戏编写 “Guess the Right Number!”?