简体   繁体   English

为什么在反转 SLL 时将 **head 发送到函数工作,而 *head 在 C 中不起作用?

[英]Why does sending **head to a function work while reversing an SLL and *head doesn't in C?

I am using Apple Clang 11.00 to compile my code to reverse a linked list.我正在使用 Apple Clang 11.00 编译我的代码以反转链接列表。 I was using this code at first but it didn't work:我起初使用此代码但它不起作用:

void reverseSLL(node *head)
{
    node *cur, *next, *prev;

    cur = head;
    prev = next = NULL;

    if (head == NULL) {
        printf("SLL does not Exist.\n");
        return;
    }

    while (cur != NULL) {
        next =  cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
    }

    head = prev;
}

Then I switched to this and it worked:然后我切换到这个并且它起作用了:

void reverseSLL(node **head)
{
    node *cur, *next, *prev;

    cur = *head;
    prev = next = NULL;

    if (*head == NULL) {
        printf("SLL does not Exist.\n");
        return;
    }

    while (cur != NULL) {
        next =  cur->next;
        cur->next = prev;
        prev = cur;
        cur = next;
    }

    *head = prev;
}

I don't understand why is this happening.我不明白为什么会这样。 Can anybody help?有人可以帮忙吗?

Arguments to functions in C are passed by value, which means that changes made to the value of the argument within the body of the function has no effect once the function returns. C 中函数的参数是按值传递的,这意味着一旦函数返回,对函数体内参数值所做的更改就不起作用。 A simple example:一个简单的例子:

void foo(int a)
{
    a += 10;
}

int main()
{
    int b = 0;
    printf("before: %d\n", b);
    foo(b);
    printf("after: %d\n", b);
    return 0;
}

This will print:这将打印:

before: 0
after: 0

If you want the calling function ( main in this case) to see the updated value, you have to pass a pointer to int (you could also return the updated value, but we'll ignore that here):如果您希望调用函数(在本例中为main )查看更新后的值,您必须传递一个指向int的指针(您也可以返回更新后的值,但我们将在此处忽略):

void foo(int *a)
{
    *a += 10;
}

int main()
{
    int b = 0;
    printf("before: %d\n", b);
    foo(&b); /* Note that we are taking the address of 'b' here */
    printf("after: %d\n", b);
    return 0;
}

In this case our output would be:在这种情况下,我们的输出将是:

before: 0
after: 10

Passing a pointer is no different.传递指针也不例外。 Making changes to the pointer in your function is not going to change it in the calling function so you have to pass a pointer to the pointer.对函数中的指针进行更改不会在调用函数中更改它,因此您必须将指针传递给该指针。 This is why your second code example works.这就是您的第二个代码示例有效的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM