簡體   English   中英

為什么在反轉 SLL 時將 **head 發送到函數工作,而 *head 在 C 中不起作用?

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

我正在使用 Apple Clang 11.00 編譯我的代碼以反轉鏈接列表。 我起初使用此代碼但它不起作用:

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;
}

然后我切換到這個並且它起作用了:

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;
}

我不明白為什么會這樣。 有人可以幫忙嗎?

C 中函數的參數是按值傳遞的,這意味着一旦函數返回,對函數體內參數值所做的更改就不起作用。 一個簡單的例子:

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;
}

這將打印:

before: 0
after: 0

如果您希望調用函數(在本例中為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;
}

在這種情況下,我們的輸出將是:

before: 0
after: 10

傳遞指針也不例外。 對函數中的指針進行更改不會在調用函數中更改它,因此您必須將指針傳遞給該指針。 這就是您的第二個代碼示例有效的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM