c - 函数什么时候必须通过引用接收参数才能改变参数的某些内容?

标签 c pointers arguments pass-by-reference

我的问题是关于以下代码(请注意,我问了一个关于代码不同区域的相关问题 here):

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int v;
    struct node * left;
    struct node * right;
};

typedef struct node Node;

struct bst
{
    Node * root;
};

typedef struct bst BST;

BST * bst_insert(BST * tree, int newValue);
Node * bst_insert_node(Node * node, int newValue);
void bst_traverseInOrder(BST * tree); 
void bst_traverseInOrderNode(Node * node);

int main(void)
{
    BST * t = NULL;

    t = bst_insert(t, 5);
    bst_insert(t, 8);
    bst_insert(t, 6);
    bst_insert(t, 3);
    bst_insert(t, 12);

    bst_traverseInOrder(t);

    return 0;
}

BST * bst_insert(BST * tree, int newValue)
{
    if (tree == NULL)
    {
        tree = (BST *) malloc(sizeof(BST));
        tree->root = (Node *) malloc(sizeof(Node));
        tree->root->v = newValue;
        tree->root->left = NULL;
        tree->root->right = NULL;

        return tree;
    }

    tree->root = bst_insert_node(tree->root, newValue);
    return tree;
}

Node * bst_insert_node(Node * node, int newValue)
{
    if (node == NULL)
    {
        Node * new = (Node *) malloc(sizeof(Node));
        new->v = newValue;
        new->left = NULL;
        new->right = NULL;
        return new;
    }
    else if (newValue < node->v)
        node->left = bst_insert_node(node->left, newValue);
    else
        node->right = bst_insert_node(node->right, newValue);

    return node;
}

void bst_traverseInOrder(BST * tree)
{
    if (tree == NULL)
        return;
    else
    {
        bst_traverseInOrderNode(tree->root);
        printf("\n");
    }
}

void bst_traverseInOrderNode(Node * node)
{
    if (node == NULL)
        return;
    else
    {
        bst_traverseInOrderNode(node->left);
        printf("%d ", node->v);
        bst_traverseInOrderNode(node->right);
    }
}

特别是,似乎我必须将 t 重新分配给 main 中的 bst-insert(t, 5) 才能实际修改t 本身,因为 bst_insert 不通过引用获取 BST *,而仅通过值获取(例如,它永远无法实际更改 BST * 本身).然而,稍后,当创建 BST 时,我可以简单地声明 bst_insert(t, 8) 这将改变 t 本身(例如改变 t-> root->left),即使它没有通过引用接收 t 作为参数。有人可以向我解释这里的区别吗?非常感谢!

最佳答案

“...因为 bst_insert 不通过引用获取 BST *,而仅通过值获取...”您使用了错误的术语,这可能是由于对下面的概念理解不清楚。

C 没有按引用传递:函数的每个参数都是按值传递的。 按值传递 意味着当调用函数时,参数被复制,函数的相应参数将获得该副本。因此,在函数内部,您使用参数的副本。

相比之下,某些语言(尤其是 C++,但不是 C)可能会通过引用 传递参数。这意味着函数中的相应参数成为参数的别名,即它可以用作同一对象的替代名称。在这种情况下,您在函数内部使用别名对对象所做的任何修改都会影响函数“外部”的参数。

在 C 中,您可以使用指针作为函数参数来更接近按引用传递行为。如果传递指针(即对象地址),则可以在函数内部使用它来间接更改指针指向的对象。

有人称此为“技巧”pass-by-pointer(或call-by-pointer),但 IMO 这个术语可能会误导那些不了解的初学者知道实际的底层机制。事实上,它根本不是什么新机制,它只是应用于指针值的按值传递!事实上,您对指针本身(与指向的对象相反)所做的任何更改都将是局部的,即不会影响您在调用中传递的实际指针。

关于c - 函数什么时候必须通过引用接收参数才能改变参数的某些内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18525292/

相关文章:

c++ - 链接外部库时出错

C 编程 - 将指针传递给数组

c++ - 如何从 win32 应用程序的命令行参数中获取 std::string?

r - 名称对应于现有函数名称的函数参数的默认值

c - 函数名转换为 uint32_t

使用查找表以低内存计算(x 指数 0.19029)?

java - "virtual"个文件

C++ 创建一个静态类来存储指针

c - 在二阶指针上使用下标运算符

function - 如何在 MATLAB 中处理函数参数的名称/值对