为什么节点* root中没有更新?

问题描述 投票:0回答:2

这是插入数字的非常简单的示例。

typedef struct node {
    int data;
    struct node *left, *right;

} node;

node * newNode(int val) {
    node* n = malloc(sizeof(node));
    n->data=val;
    n->left=NULL;
    n->right=NULL;
    return n; }

void insert(node* node, int key) {    
    if (node == NULL)
        node = newNode(key);
}

int main() {
    node *root = NULL;
    insert(root, 5);

    printf("%d\n", root->data);

    return 0;
}

问题是,为什么当我在printf中插入5时root什么都不打印?

c struct binary-search-tree pass-by-reference
2个回答
2
投票

在C中,所有参数都传递按值”。这意味着该值被copied放入参数变量,并且当您执行分配node = newNode(key);时,您仅分配给本地node变量。

对此问题有两种解决方案:

  1. Return改为新节点:

    node* insert(node* the_node, int key) {    
        if (the_node == NULL)
            the_node = newNode(key);
        return the_node;
    }
    
    ...
    
    root = insert(root, 5);
    
  2. 仿真通过引用传递,可以通过使用地址运算符&传递指向变量的指针来完成:

    void insert(node** the_node, int key) {    
        if (*the_node == NULL)
            *the_node = newNode(key);
    }
    
    ...
    
    insert(&root, 5);
    

1
投票

您已按值将指针root传递给函数insert。您可以通过以下方式想象函数声明及其调用]

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