简体   繁体   中英

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. 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. 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):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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