首页 > 解决方案 > 在函数中传递双指针

问题描述

我正在用 C 语言创建一个带有链表的程序。我在函数中创建了一个head变量。main然后我通过引用一个函数来传递它insert_at_head(struct node **head)

我有另一个在尾部插入的功能。在基本条件下,如果我的列表为空,我想insert_at_head(struct node **head)再次调用。但是我在传递实际参数时感到困惑。应该是insert_at_head (&(*head))还是insert_at_head (head)

就个人而言,我认为两者都是相同的,因为它们都传递了一个双指针。我应该使用哪一个?

标签: cpointerslinked-listparameter-passing

解决方案


关于insert_at_head函数,您必须记住,在 C 中,所有参数都是按值传递的。这意味着该值被复制到参数变量中。在函数内部,如果您修改参数变量(例如分配给它),那么您只修改副本,而不是原始变量。

如果要修改原始值,则必须模拟 pass by reference,这可以通过使用 address-of 运算符&传递指向该值的指针来完成。如果您想对作为指针的变量执行此操作,那么您将获得指向指针的指针。

这是一个简单的例子:

#include <stdio.h>

// Define two global variables
int a = 10;
int b = 20;

void change1(int *x)
{
    x = &b;  // Make x point to b
}

void change2(int **x)
{
    *x = &b;  // Make *x point to b
}

int main(void)
{
    // Define a pointer variable, and make it point to the global variable a
    int *pointer_to_a = &a;

    // Will print the value of a, i.e. 10
    printf("*pointer_to_a = %d\n", *pointer_to_a);

    // Try to change where pointer_to_a is pointing
    change1(pointer_to_a);

    // Here pointer_to_a is *still* pointing to a, it wasn't changed, will print the value 10
    printf("*pointer_to_a = %d\n", *pointer_to_a);

    // Do another attempt to change where pointer_to_a is pointing
    change2(&pointer_to_a);

    // Now pointer_to_a is no longer pointing to a, it points to b and 20 will be printed
    printf("*pointer_to_a = %d\n", *pointer_to_a);
}

回到insert_at_head函数(我们只能推测其功能)我猜它会添加到链表的头部。它将通过修改列表头指向的位置来做到这一点。

从上面的例子可以看出,除非我们将指针传递给指针,否则一旦函数结束,对头部的赋值就会丢失。这可以通过使用指向指针的指针来解决,并&在调用函数时使用地址运算符传递头指针。


推荐阅读